I am trying to learn MVC and have been stuck on this for quite some time, all the tutorial online uses strongly typed view but my view isn't strongly typed,
@using (Html.BeginForm("addInventory", "AdminController", FormMethod.Post))
{
<div class="form-style-2-heading">Add New Inventory</div>
<label>
<span>No <span class="required">*</span></span>@Html.TextBox("no", null, new { id = "no", Class = "input-field" })
</label>
<label>
<span>Name <span class="required">*</span></span>@Html.TextBox("name", null, new { id = "name", Class = "input-field" })
</label>
<label>
<span>Primary Type <span class="required">*</span></span>@Html.DropDownList("typeList", ViewBag.typeList as SelectList, new { id = "primarytype", Class = "select-field" })
</label>
<label>
<span>Secondary Type <span class="required">*</span></span>@Html.DropDownList("typeList", ViewBag.typeList as SelectList, new { id = "secondarytype", Class = "select-field"})
</label>
<label><span> </span><input type="submit" value="Submit" /></label>
}
So I successfully binded my dropdown list with data from the controller but I can't seem to do it the other way round
Edit:
Model:
public class inventoryModel
{
public int no { get; set; }
public string name { get; set; }
public int primaryType { get; set; }
public int secondaryType { get; set; }
}
Controller:
private ActionResult addInventory()
{
return View();
}
Your error is here:
<label>
<span>Primary Type <span class="required">*</span></span>
@Html.DropDownList("primaryType", (IEnumerable<SelectListItem>)ViewBag.typeList, new { @class = "select-field" })
</label>
<label>
<span>Secondary Type <span class="required">*</span></span>
@Html.DropDownList("secondaryType", (IEnumerable<SelectListItem>)ViewBag.typeList, new { @class = "select-field"})
</label>
Don't use id in htmlAttributes 1st helper parameter is used for tag id
and name
on POST value of tag will bind to your model property by name
.
Also note that I escape class
name with @
symbol.
On POST here what your controller signature should be:
[HttpPost]
private ActionResult addInventory(inventoryModel model)
{
var data = model.secondaryType; //here you can get your posted data
return View();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.