MVC 4 Form - submit button doesn't do anything - asp.net-mvc-4

Trying to implement a form in MVC4 (+Razor), but submit button is not doing anything.
Controller (that should get the post action):
public class GeneralController
{
[HttpPost]
public ActionResult SearchResults(SearchParamsModel searchParams)
{
// doin some stuff here
return View("SearchResultsView");
}
}
View (.cshtml)
#model Models.SearchParamsModel
#using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
<section class="form-field">
<input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" />
<label for="Property1">value1</label>
<form action="" method="post" class="clearfix">
<input type="submit" value="some value" class="submit btn blue-btn special-submit" />
</form>
</section>
}
Model
public class SearchParamsModel
{
public string Property1{ get; set; }
}

If you just need to implement searching you don't need to use ViewModel, you may send string with search request. And it shouldn't be Post method:
public ActionResult SearchResults(string searchString)
{
//code for searching
return View(yourmodel);
}
In View
#using (Html.BeginForm())
{
Searching: #Html.TextBox("SearchString")
<input type="submit" value="Search"/>
}

The Html.BeginForm helper will create the form tags for you, try it...
View:
#model Models.SearchParamsModel
#using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
<section class="form-field">
<input type="text" name="Property1" id="Property1" class="field
field139 autocomplete-init-no-img" />
<label for="Property1">value1</label>
<input type="submit" value="some value"
class="submit btn blue-btn special-submit" />
</section>
}

if I do the same in MVC 4 or 5 I get the same result.
look at adding <fieldset> tags around all controls:
#using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
<fieldset>
// your controls...
<input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" />
<label for="Property1">value1</label>
<input type="submit" value="some value" class="submit btn blue-btn special-submit" />
// if you need a partial form included:
#{Html.RenderPartial("_SomeOtherPartial", #Model);}
// etc..
</fieldset>
}
Give that a try...
Let me know

Related

Setting properties using asp-for in MVC Core App with EF Core?

As I understand it from these docs: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1 , asp-for is used to transfer values from input elements to backend C# class properties, for example:
<input type="text" id="wsite" name="wsite" maxlength="11" asp-for="WebsiteName">
Along with '#folderName ClassName;' at the top, lets you transfer to this example property:
public string WebsiteName { get; set; }
However, testing this out with console.WriteLine show that the property is still null after the form containing the input has been submitted. Any idea what I'm missing?
Edit: Updated to show my property name and asp-for value match, and to add my controller:
[HttpPost]
public IActionResult Post()
{
DBCRUD.Initialize(_context);
return NoContent();
}
The asp-for tag should match the variable-name.
Try defining your html-form like:
#model Classname
<form asp-action="ActionName" asp-controller="ControllerName" ...>
<input type="text" asp-for="VarName">
and your controller:
public MyReturnVariable ActionName(ClassName class) {
Console.WriteLine(class.VarName);
}
The Tag Helpers is used with Model binding and creating and rendering HTML elements(display the model properties) in the web page.
So, in the Web page (or view page), at the top of the header, we should add the following code to assign the model.
#model MVCSample.Models.BookModel
Then, using the following code to display the properties:
<div class="row">
<div class="col-md-4">
<form asp-action="AddBook">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ID" class="control-label"></label>
<input asp-for="ID" class="form-control" />
<span asp-validation-for="ID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="bookName" class="control-label"></label>
<input asp-for="bookName" class="form-control" />
<span asp-validation-for="bookName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Code in the controller:
[HttpGet]
public IActionResult AddBook()
{
BookModel book = new BookModel()
{
ID = 1001,
bookName = "War and Peace",
Title = "War and Peace"
};
return View(book);
}
Code in the model:
public class BookModel
{
public int ID { get; set; }
public string bookName { get; set; }
public string Title { get; set; }
}
More details information, you could check the Model Binding.

bool value render asp-for for checkbox but it always get True value not false in mvc core razor view?

<div class="checkbox">
<label>
<input type="checkbox" class="checkbox style-0" asp-for="Approver" />
<span>Approval</span>
</label>
</div>
Always get true value not false whenever check or not check checkbox.
Firstly,the usage of <input type="radio" class="checkbox style-0" asp-for="Approver" /> in my view is wrong,because the value is null.
Here is a demo:
Controller:
public IActionResult Test()
{
Genders g = new Genders();
g.genders = new List<string> { "Male", "Female", "Unspecified" };
return View(g);
}
[HttpPost]
public IActionResult Test(String gender) {
return View();
}
Genders:
public class Genders
{
public List<string> genders { get; set; }
}
View:
<form method="post">
#foreach(var gender in Model.genders){
<div>
<input type="radio" name="Gender" value="#gender" />#gender<br />
</div>
}
<input type="submit" value="submit" />
</form>
result:
It is radio option for only true false, so you can do it in simple way without iterating any collection.
<div>
<input type="radio" name="check" value="1"> true<br />
<input type="radio" name="check" value="0"> false<br />
</div>
Just use onchange javascript function if not able to bind value in model bool property.
<input asp-for="Approver" type="checkbox" value="false"
onchange="this.value=this.checked" />

Checkbox list values empty when ModelState is not valid and ASP.NET Core does return Page()

I created an ASP.NET Core 3.1 project. I have a form in it with several checkbox lists. I can get the values into the properties in POST and they are correctly filled in (e.g. List SelectedItems). However for some custom fields I have to do a validation in OnPost() method and if the conditions are not met or a ModelState is not valid, it return Page(). Normally I would expect that every property that was filled in in the form is still filled in, but the checkboxes are always empty and not a single one is checked. The other data (radio buttons, textboxes, etc.) are still filled in.
I even tried to put the values within the Razor page, but even then neither of the checkboxes was checked.
Here is an example of one of the checkboxes:
In Razor page:
#for (var i = 1; i <= 10; i++){
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name="AreChecked" />}
Behind code:
[BindProperties]
public class TestFormModel : PageModel
{
[BindProperty]
public List<int> AreChecked { get; set; }}
public IActionResult OnPost()
{
//some other form check statements here
//...
if (ModelState.IsValid)
{
//process data code...
}
return Page();
}
Can someone help me with this?
You could use JQuery to achieve as shown :
#page
#model RazorPages3_1.AddimgModelModel
<div class="row">
<div class="col-md-4">
<form enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Petimg.PetName" class="control-label"></label>
<input asp-for="Petimg.PetName" class="form-control" />
<span asp-validation-for="Petimg.PetName" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="Uploads" class="form-control" />
</div>
#for (var i = 1; i <= 10; i++)
{
<input name="AreChecked" type="checkbox" id="#i" value="#i" /> #i<br />
<input type="hidden" value="true" id="#i" name=""AreChecked" />
}
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-page="Index">Back to List</a>
</div>
#section Scripts {
<script>
var checkedlist = #Html.Raw(Json.Serialize(Model.AreChecked));;
if (checkedlist.length > 0) {
$.each(checkedlist, function (index, value) {
$('input[type=checkbox]').each(function () {
var id = $(this).attr("id");
if (id == value) {
$(this).attr('checked', 'checked');
}
})
});
}
</script>
}
Result

Not Receiving Multiple Partial View data on Postback

Please can you help on the below query.
I have got a main view and partial view. In main view looping through based on the count of model, the partial views will be rendered. The Partial View is as per below
-----------------Partial View----------------------
#using (Html.BeginCollectionItem("books"))
{
<div id="bookRow" class="bookRow">
<div class='container'>
<div class="align-left">
<h1>Book Name</h1>
<h2>#Html.TextBoxFor(m => m.BookName)</h2>
</div>
<div class="align-right">
<h1>Author</h1>
<h2>#Html.TextBoxFor(m => m.Author)</h2>
</div>
<div class="align-right">
<h1>Publisher</h1>
<h2>#Html.TextBoxFor(m => m.Publisher)</h2>
</div>
<div class="align-right">
#Html.CheckBoxFor(model => model.isConfirm)
#Html.Hidden("Id", #Model.Id)
</div>
Delete
</div>
</div>
}
-------------------Main View----------------------
#model IEnumerable<TDLProject.Models.BookViewModel>
<fieldset>
<legend>Books</legend>
<div id="new-Book">
#foreach (var model in Model)
{
#Html.Partial("_DynamicPartialView", model)
}
</div>
<div>
<input type="button" id="addBook" name="addBook" value="Add Book" />
<br />
</div>
<br />
</fieldset>
#using (Html.BeginForm())
{
<div>
<input type="submit" id="submitButton" value="Submit" />
</div>
}
-------------Controller--------------
[HttpPost]
public ActionResult Contact(IEnumerable<BookViewModel> bookModel)
{
// To do: do whatever you want with the data
return View();
}
The Problem is I am not receiving the data posted from View to the Controller on Click of Submit button. I have multiple partial views of same model on the main view and when click of submit button I need all the partial view data to posted to controller. In Partial View I am using BeginCollectionItem. Please can you help on this.
A form only posts back the name/value pairs of its successful controls, and your not generating the form controls inside the <form> tags.
Change the code to move the #Html.Partial() code inside the <form> (simplified)
#model IEnumerable<TDLProject.Models.BookViewModel>
#using (Html.BeginForm())
{
#foreach (var model in Model)
{
#Html.Partial("_DynamicPartialView", model)
}
<input type="button" id="addBook" name="addBook" value="Add Book" />
<input type="submit" id="submitButton" value="Submit" />
}
You also need to change the POST method signature to
public ActionResult Contact(IEnumerable<BookViewModel> books)
to match the name you use in the #using (Html.BeginCollectionItem("books")) method.

choosing between 2 actions in one controller with single view by checkbox

I got 2 actions in my controller, I want to choose which action to execute by checkbox in my razor view.
here is my controller:
public ActionResult Person(string searchString)
{
var person = from p in db.Persons
select p;
if (!String.IsNullOrEmpty(searchString))
{
person = person.Where(oo => oo.Name.ToUpper() == searchString);
}
return View(person);
}
public ActionResult Job(string jobString)
{
var jobs = from j in db.Jobs
select j;
if (!String.IsNullOrEmpty(jobString))
{
jobs = jobs.Where(oo => oo.Name.ToUpper() == jobString);
}
return View(jobs);
}
when I check a case I would like to execute the query search for this specific case
here is my view:
<div>
<form method="POST">
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
#using (Html.BeginForm())
{
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
</form>
Post to a single action method, then call one of your existing methods depending on the value of the checkbox.
public ActionResult Search(bool isJobSearch, string searchString)
{
if (isJobSearch)
{
return Job(searchString);
}
else
{
return Person(searchString);
}
}
private ActionResult Person(string searchString)
{
// As your example
}
private ActionResult Job(string jobString)
{
// As your example
}
I am just correcting your html
Your html contains two form tags. I am not sure about the usage of form with in form tags. html.beginform will create internally another form tag when gets executed.So better one form tag will contain all elements to make a post.
#using (Html.BeginForm("Search","Home"))
{
<div>
<input type="checkbox" name="Person" value="Person" style="margin-left: 54px"/>Person
</div>
<div class="Job">
<input type="checkbox" name="Job" value="Job" />Job
</div>
<p>
<input type="text" name="SearchString" style="margin-left: 90px;" />
<input type="submit" value="Search" />
</p>
}
}
in controller
public ActionResult Search(FormCollection form)
{
//do some condition based on your needs
if(form["SearchString"]=="Job")
return RedirectToAction("Job");
else
return RedirectToAction("Person");
}
public ActionResult Person()
{
}
public ActionResult Job()
{
}