I added a dynamically added object like:
@Html.EditorFor(model => model.Province)
My model contains the Province properties but the view didn’t show the object at the begining. I made it visible by .show() method.
However, in the controller, I found always the value for Province is null. How to make it accessible from dynamically added object like this?
Added:
my model looks like this:
public class Location
{
[Required]
public int ID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public string Street { get; set; }
public string City { get; set; }
[Display(Name = "State/Province")]
public string Province { get; set; }
}
controller:
[HttpPost]
public ActionResult Create(Location location)
{
if (ModelState.IsValid)
{
db.Location.Add(location);
db.SaveChanges();
return RedirectToAction("Index");
}
}
view:
<div class="editor-label">
@Html.LabelFor(model => model.Province)
</div>
<div class="editor-field">
<div id="province_ddl">
@Html.DropDownListFor(
x => x.Province,
Enumerable.Empty<SelectListItem>(),
"-- Select State/Province --"
)
</div>
<div id="province_tb" style="display: none">
@Html.EditorFor(model => model.Province)
</div>
@Html.ValidationMessageFor(model => model.Province)
</div>
When I use dropdownlist, it will have right value for Province property. However, if I made textbox control visible, it won’t have value i.e., got null value in the controller.
You cannot have 2 input fields in the same form with the same name (
Provincein your case). Well, actually you can but only the value of the first will be sent to the controller. So if you keep the dropdown it will be the selected value of the dropdown that will always be sent to the controller. So basically you have to decide. You might disable one of the fields (by adding thedisabled="disabled"attribute to it, could be done dynamically) to force only the value of the other to be sent.