DisplayFor helper方法呈现实体的ID,但不会沿POST表单集合传递它

Onl*_*ere 2 c# post controller view asp.net-mvc-3

我很确定这是因为提交表单时表单只输入POSTS,不是吗?

因此,当我收到POST响应时,我正确接收了我编辑的名称,但ID始终设置为0.

任何解决方法?

public ActionResult Edit(int id)
{
    var productBrand = brandRepo.FindProductBrand(id);
    ProductBrandModel model = Mapper.Map<ProductBrand, ProductBrandModel>(productBrand);
    return View(model);
}

[HttpPost]
public ActionResult Edit(ProductBrandModel model)
{
    if (ModelState.IsValid)
    {
        var productBrand = brandRepo.FindProductBrand(model.ProductBrandId);
        productBrand.Name = model.Name;
        brandRepo.SaveChanges();
        return RedirectToAction("Index", "ProductBrands");
    }
    return View(model);
}


/* THIS IS THE VIEW*/

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>ProductBrandModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductBrandId)
        </div>
        <div class="editor-field">
            @Html.DisplayFor(model => model.ProductBrandId)
        </div> 

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>  

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
Run Code Online (Sandbox Code Playgroud)

我不想让用户编辑实体的ID,只编辑名称.

谢谢.

its*_*att 5

添加怎么样?

@Html.HiddenFor(model => model.ProductBrandId)

如果我理解你的问题,我认为这会做你想要的.