0

我正在尝试以编辑模式保存实体。我想使用 FormCollection 将值从 View 传递到控制器,但没有值进入控制器。

这是标记:

 @using (Html.BeginForm("Edit", "Product", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmCreate" }))
{
    <div class =" row-fluid Span12" style ="margin-bottom :15px">
        <div class="span6" >
            <div class ="span4">
                <label>Product Name</label>
            </div>
            <div class ="span6">
                 <input type="text" value="@ViewBag.Name" id="ProductName" name="ProductName" style="height:20px; width:100%;" />
            </div>
        </div>
        <div class="span6" >
            <div class="span4" >
            <label > Product Code</label>
        </div>
        <div class="span6" >
            <input  type="text" value="@ViewBag.SectionCode" id="SectionCode"/> 
        </div>
    </div>
    <div class="span11" style="text-align:right">
        <input class="btn btn-primary" type="submit" value="Save" id="Edit"/>
        <button class="btn btn-default">Cancel</button>
    </div>
           }   

这是我的控制器代码

[HttpPost]
public ActionResult Edit(FormCollection form)
{
    Product product = new Product();
    product.SectionCode = Convert.ToString(form["SectionCode"]);
    product.Name = Convert.ToString(form["Name"]);

    return RedirectToAction("SaveData", oProductNew);
}

没有值进入 FormCollection。

4

2 回答 2

0

试试这个怎么样。在您的[HttpGet]方法中,您执行以下操作:

    [HttpGet]
    public ActionResult Edit()
    {
        Product product = new Product();
        return View(product);
    }

要将您[HttpPost]的代码更新为(这应该可以很好地用于绑定):

    [HttpPost]
    public ActionResult Edit(Product product)
    {
        return RedirectToAction("SaveData", product);
    }

最后,您可以更新您的视图以将产品作为视图模型:

    @model YourNamespace.Product @* Page View Model *@      
    @using (Html.BeginForm("Edit", "Product", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmCreate" }))
    {
        <div class =" row-fluid Span12" style ="margin-bottom :15px">
            <div class="span6" >
                <div class ="span4">
                    <label>Product Name</label>
                </div>
                <div class ="span6">
                    @Html.TextBoxFor(x => x.ProductName, new { @Style = "height:20px; width:100%;" }) @* TextBoxFor Extension Method *@
                </div>
            </div>
            <div class="span6" >
                <div class="span4" >
                <label > Product Code</label>
            </div>
            <div class="span6" >
                @Html.TextBoxFor(x => x.SectionCode)  @* TextBoxFor Extension Method *@          
            </div>
        </div>
        <div class="span11" style="text-align:right">
            <input class="btn btn-primary" type="submit" value="Save" id="Edit"/>
            <button class="btn btn-default">Cancel</button>
        </div>
    }   

@Html扩展方法将创建数据绑定自动发生所需的所有名称和 ID 。

于 2014-02-27T06:58:34.183 回答
0

可能,您的视图代码不属于表单。将其放入表单并尝试提交。

于 2014-02-27T06:47:57.723 回答