MVC将数据从非强类型视图传递到控制器

时间:2016-07-20 06:22:08

标签: c# asp.net asp.net-mvc

我正在尝试学习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>&nbsp;</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();
}

1 个答案:

答案 0 :(得分:0)

您的错误在这里:

<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第一个帮助参数用于标记idname用于 POST 标记的值将{{1}绑定到您的模型属性}}

另请注意,我使用name符号转义class名称。

在POST这里你的控制器签名应该是:

@