MVC将数据从非强类型视图传递到控制器
本文关键字:控制器 视图 强类型 数据 MVC | 更新日期: 2023-09-27 17:57:42
我正在努力学习MVC,并且已经坚持了很长一段时间,所有在线教程都使用强类型视图,但我的视图不是强类型的,
@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>
}
所以我成功地将我的下拉列表与控制器的数据绑定在一起,但我似乎无法用的其他方式
编辑:
型号:
public class inventoryModel
{
public int no { get; set; }
public string name { get; set; }
public int primaryType { get; set; }
public int secondaryType { get; set; }
}
控制器:
private ActionResult addInventory()
{
return View();
}
您的错误在这里:
<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>
不要在htmlAttributes中使用id。POST上的标记id
和name
使用第一个辅助参数。标记的值将通过name
绑定到您的模型属性。
还要注意,我用@
符号转义class
名称。
在POST上,您的控制器签名应该是:
[HttpPost]
private ActionResult addInventory(inventoryModel model)
{
var data = model.secondaryType; //here you can get your posted data
return View();
}