Not able to bind html.checkbox on form post - asp.net-mvc

So I have a view model call ProductViewModel which has a list of sites where a product can be produced. I am trying to figure out how to show this on a form using a checkbox for the user to select the sites where the product can be produced. Seems straight forward, right? Well it doesn't work like I want/need. Hoping someone can help guide me to the correct way to do this.
My classes:
public class ProductViewModel
{
public List<Sites> SiteList {get; set;}
public string ProductName {get; set;}
public int ProductId {get; set;}
public User ProductOwner{get; set;}
}
public class Sites
{
public int SiteId {get; set;}
public string SiteName {get; set;}
public bool IsSelected {get; set;}
}
Part of my view:
#Html.LabelFor(m=>m.Sites):
#foreach (var site in Model.Sites)
{
#Html.CheckBox("Sites", site.IsSelected, new { value = site.SiteName })
#Html.Label(site.SiteName)
}
When using #Html.Checkbox() I see the following output in the html from the browser:
<input checked="checked" id="Sites" name="Sites" type="checkbox" value="Miami" />
<input name="Sites" type="hidden" value="false" />
I understand the hidden field but what I really need is to get the value for the selected item. So I need to get back the list with Miami in it. I don't need the false/true thing that the html helper seem to want to send (i.e. Miami=true)
So instead I tried this.
#for(int id=0; id < Model.Sites.Count(); id++)
{
<input type="checkbox" id="#Model.Sites[id].SiteName" name="Sites[#id]" value="#Model.BoxingSites[id].SiteName" #(Model.Sites[id].IsSelected ? #"checked=""checked""": "") />
#Html.Label(Model.Sites[id].SiteName)
}
And the output is:
<input type="checkbox" id="Miami" name="Sites[0]" value="Miami" checked="checked" />
<label for="Miami">Miami</label>
In both of these cases I am not able to get the binder to map the form values to the Product.Sites list when posting to the action.
The action is like this:
[HttpPost]
public ActionResult Edit(ProductViewModel Product)
{
//Does something with the form data.
}
The other values (ProductName etc...) map fine.
What am I doing wrong? I feel I am missing something as this should be easier due to how MVC simplifies so many other form handling situations.
Thanks in advance...

How about using an editor template instead of struggling with loops:
#model ProductViewModel
#using (Html.BeginForm())
{
... some other form fields
#Html.LabelFor(x => x.SiteList)
#Html.EditorFor(x => x.SiteList)
<input type="submit" value="Create" />
}
and inside the corresponding editor template ~/Views/Shared/EditorTemplates/Sites.cshtml:
#model Sites
<div>
#Html.HiddenFor(x => x.SiteId)
#Html.CheckBoxFor(x => x.IsSelected)
#Html.LabelFor(x => x.SiteName)
</div>
Now not only that your view code is much more clean but proper names will be generated for the input fields so that the model binder will be able to bind the selected values back in the POST action.
[HttpPost]
public ActionResult Create(ProductViewModel model)
{
...
}

Here is what is working for me.
// View Model
[Display(Name="Boolean Property")]
[UIHint("booleancheckbox"]
public bool? booleanProperty;
View
// View
#Html.EditorFor(m => m.booleanProperty, new { #onclick = "Toggle(this);" })
Editor Template - add some more code to handle null values
// Editor Template booleancheckbox.cshtml
#model bool?
#{
labelText = ViewData.ModelMetadata.DisplayName != null ?
ViewData.ModelMetadata.DisplayName :
ViewData.ModelMetadata.PropertyName;
}
<label for="#ViewData.ModelMetadata.PropertyName">#labelText
#Html.CheckBox(string.Empty, Model.Value, ViewContext.ViewData)
</label>

Related

Update a field in view based on the model in ASP.NET MVC

I need to do a calculator in ASP.NET MVC.
For the beginning I want to receive the value from the input field in controller and prefix it with the string "123". At the end I will process the expresion received and return the result.
I have the following model:
namespace CalculatorCloud.Models {
public class Calculator
{
public string nr { get; set; }
} }
In the view I am using the model:
#model CalculatorCloud.Models.Calculator
#{
ViewBag.Title = "Calculator";
}
#using (Html.BeginForm("Index", "Home"))
{
<div>
<div class="header">
#Html.TextBoxFor(m => m.nr, new { #id = "nr"})
<input type="button" id="C" name="C" value="C" />
<input type="button" id="back" name="back" value="<-" />
[...]
<div class="sum">
<input type="submit" value="=" />
</div>
</div>
}
The controller is like this:
namespace CalculatorCloud.Controllers
{
public class HomeController : Controller
{
Calculator model = new Calculator();
public ActionResult Index(string nr)
{
model.nr = "123" + nr;
return View(model);
}
}
}
I have the following problem: when pressing on submit button I am expecting to be displayed on the textbox the value from that was previously in the textbox, prefixed with the string "123".
But now it is kept the value from the textbox without the string "123".
Can someone help me with this?
Thank you! :)
If you want to modify the value of a model property in a postback action you will need to remove it from the ModelState:
public ActionResult Index(string nr)
{
ModelState.Remove("nr");
model.nr = "123" + nr;
return View(model);
}
The reason for this is that Html helpers such as TextBoxFor will first look at the value present in the ModelState and then in your view model property when rendering the value. This is by design.

List Binding with model data

So I have a form that I am trying to submit and I can get either the list or the model to bind, but not both at the same time. I suspect it has to do with the model binder.
HTML
#using (Html.BeginForm("Index", "Home", FormMethod.Post)){
#Html.AntiForgeryToken()
<div class="TransferHeader">
<div>
#Html.LabelFor(model => model.tranRequestedBy)
#Html.EditorFor(model => model.tranRequestedBy, new { #Name = "h.tranRequestedBy" })
</div>
<div>
#Html.LabelFor(model => model.tranNotes)
#Html.EditorFor(model => model.tranNotes, new { #Name = "h.tranNotes" })
</div>
<input name="h.TransfersDetail.Index" id="detIndex" type="hidden" value="c3a3f7dd-41bb-4b95-b2a6-ab5125868adb">
<input name="h.TransfersDetail[c3a3f7dd-41bb-4b95-b2a6-ab5125868adb].detToolCode" id="detToolCode" type="hidden" value="1234">
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(TransfersHeader h)
{
return View();
}
Model Class:
public virtual ICollection<TransfersDetail> TransfersDetail { get; set; }
public string tranRequestedBy { get; set; }
public string tranNotes { get; set; }
The two bottom inputs were generated from an AJAX call to an add method, what happens is if they are not present the two HTML helper editors will come in the model, but if they do exist only the transfer detail list will appear.
Is there anything I could do to make sure all of the data comes into the model?
Its not clear how you are generating those inputs, but the name attributes are incorrect. You model does not contain a collection property named h, but it does contain one named TransfersDetail, so your inputs need to be
<input name="TransfersDetail.Index" type="hidden" value="c3a3f7dd-41bb-4b95-b2a6-ab5125868adb">
<input name="TransfersDetail[c3a3f7dd-41bb-4b95-b2a6-ab5125868adb].detToolCode" type="hidden" value="1234">
Its also not clear why your adding an id attribute (if you referencing collection items in jQuery, you would be better off using class names and relative selectors), but the id your using does not have an indexer suggesting that your going to be generating duplicate id attributes which is invalid html (and jQuery selectors would not work in any case)

Sending up a list of objects on a create form

I have a view specific model that combines a few of my objects together but I was having a few issues with a list of objects.
My model is so:
public class RouteSubcontract
{
public RoutingSubcontracts Subcontracts { get; set; }
public RoutingPhases Phases { get; set; }
public List<RoutingApprovals> Approvals { get; set; }
}
I have my create form and everything is working correctly, I am using html helpers like so:
#Html.EditorFor(model => model.Subcontracts.subRevNbr, new { htmlAttributes = new { #class = "textReplace", #id = "frmRevNbr" } })
But the problem is when I need to have the list of approvals, I am not even sure how to start with this. I need the ability to create a list of items, I can with jquery have a button that then creates the row of textboxes I need to enter the data, but I am unsure how to ID or name them so that they are picked up correctly by my post back.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AdminRoutingCreate(RouteSubcontract rs)
For collections the modelbinder expects inputs named in the following format: ListProperty[Index].Property. For example, if you wanted to edit a property on RoutingApprovals named Foo, you're need something like:
<input type="text" name="Approvals[0].Foo" />
<input type="text" name="Approvals[1].Foo" />
<input type="text" name="Approvals[2].Foo" />
On post back you'd end up with three RoutingApprovals instances.

How To Pass Value Entered In A Text Box To An Action Method

I was building a Movies application using MVC. CRUD was automatically created for me by Visual Studio. Now, I am trying to build a Search functionality for the user. Here is the code I wrote:
#using (Html.BeginForm("SearchIndex", "Movies", new {searchString = ??? }))
{
<fieldset>
<legend>Search</legend>
<label>Title</label>
<input type ="text" id="srchTitle" />
<br /><br />
<input type ="submit" value="Search" />
</fieldset>
}
I have built the SearchIndex method and the associated view. I just can't find how to pass the value entered in the text box to the SearchIndex action method.
Please help.
In your Model:
public class Search
{
public String SearchText { get; set; }
}
Make your View strongly typed and use
#Html.EditorFor(model => model.SearchText)
In your Controller:
[HttpPost]
public ActionResult SearchIndex(Search model)
{
String text = model.SearchText;
}
Hope this helps.
You need to give your input field a name:
<input type="text" id="srchTitle" name="movieToFind" />
Then in your Controller make sure it has a string parameter:
in MoviesController:
[System.Web.Mvc.HttpPost]
public ActionResult SearchIndex(string movieToFind)
{
//Controller Action things.
}
Note: Form fields names must match the parameters expected in the controller. Or map to model properties if a 'Model' is expected.

ASP.NET MVC, passing Model from View to Controller

I'm having trouble with ASP.NET MVC and passing data from View to Controller. I have a model like this:
public class InputModel {
public List<Process> axProc { get; set; }
public string ToJson() {
return new JavaScriptSerializer().Serialize(this);
}
}
public class Process {
public string name { get; set; }
public string value { get; set; }
}
I create this InputModel in my Controller and pass it to the View:
public ActionResult Input() {
if (Session["InputModel"] == null)
Session["InputModel"] = loadInputModel();
return View(Session["InputModel"]);
}
In my Input.cshtml file I then have some code to generate the input form:
#model PROJ.Models.InputModel
#using(Html.BeginForm()) {
foreach(PROJ.Models.Process p in Model.axProc){
<input type="text" />
#* #Html.TextBoxFor(?? => p.value) *#
}
<input type="submit" value="SEND" />
}
Now when I click on the submit button, I want to work with the data that was put into the textfields.
QUESTION 1: I have seen this #Html.TextBoxFor(), but I don't really get this "stuff => otherstuff". I concluded that the "otherstuff" should be the field where I want to have my data written to, in this case it would probably be "p.value". But what is the "stuff" thing in front of the arrow?
Back in the Controller I then have a function for the POST with some debug:
[HttpPost]
public ActionResult Input(InputModel m) {
DEBUG(m.ToJson());
DEBUG("COUNT: " + m.axProc.Count);
return View(m);
}
Here the Debug only shows something like:
{"axProc":[]}
COUNT: 0
So the returned Model I get is empty.
QUESTION 2: Am I doing something fundamentally wrong with this #using(Html.BeginForm())? Is this not the correct choice here? If so, how do I get my model filled with data back to the controller?
(I cannot use "#model List< Process >" here (because the example above is abbreviated, in the actual code there would be more stuff).)
I hope someone can fill me in with some of the details I'm overlooking.
Change your view to some thing like this to properly bind the list on form submission.
#using(Html.BeginForm()) {
for(int i=0;i<Model.axProc.Count;i++){
<span>
#Html.TextBoxFor(model => model.axProc[i].value)
</span>
}
<input type="submit" value="SEND" />
}
In #Html.TextBoxFor(stuff => otherstuff) stuff is your View's model, otherstuff is your model's public member.
Since in the View you want to render input elements for the model member of a collection type (List), you should first create a separate partial view for rendering a single item of that collection (Process). It would look something like this (name it Process.cshtml, for example, and place into the /Views/Shared folder):
#model List<PROJ.Models.Process>
#Html.TextBoxFor(model => p.value)
Then, your main View would look like this:
#model PROJ.Models.InputModel
#using(Html.BeginForm()) {
foreach(PROJ.Models.Process p in Model.axProc){
#Html.Partial("Process", p)
}
<input type="submit" value="SEND" />
}
Also, check that the loadInputModel() method actually returns something, e.g. not an empty list.

Resources