【问题标题】:@Html.Partial in Ajax.BeginForm does not post data to actionAjax.BeginForm 中的@Html.Partial 不会将数据发布到操作中
【发布时间】:2011-09-14 05:28:15
【问题描述】:

当我尝试发布数据并从具有局部视图的视图中调用操作时,我没有获得局部视图的模型数据,但是当我直接使用它而不是局部视图时,它会正确发送数据。

<div id="mydiv">
    @using (Ajax.BeginForm("Index1", "Home", new AjaxOptions { UpdateTargetId = "mydiv", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" }))
    {        
        //Does not send data to action on post  
        @Html.Partial("ViewUserControl1",Model.Emps)
        //ViewUserControl1 contains the same next 8 line logic.
        OR

        //Send the data to actions on post.
        for (int i = 0; i < Model.Emps.Count(); i++)
        {
            @Html.TextBoxFor(x => x.Emps[i].Name)
            @Html.TextBoxFor(x => x.Emps[i].Address)
            @Html.ValidationMessageFor(x => x.Emps[i].BBString)
        <br />    
        }

        <input id="dosomething" type="submit" value="save" />
    }
</div>


///On Controller 
   [HttpPost]
   public ActionResult Index1(MyModel model)
   {
      ///Here i am looking for the model data which is null for partial.
      return View(model);
   }

MyModel 有一个 Emps 列表 { Name,Address}

有谁知道这是什么原因。

【问题讨论】:

  • 在此处发布您的Index1 操作。
  • ViewUserControl1 部分包含什么?
  • ViewUserControl1 包含相同的下 8 行。

标签: asp.net-mvc razor


【解决方案1】:

我怀疑你的ViewUserControl1 部分看起来像这样(你没有展示它,你只是说它看起来像下面的 8 行,但显然它看起来不像那 8 行,因为它使用了不同的视图型号):

@model IEnumerable<Employee>

for (int i = 0; i < Model.Count(); i++)
{
    @Html.TextBoxFor(x => x[i].Name)
    @Html.TextBoxFor(x => x[i].Address)
    @Html.ValidationMessageFor(x => x[i].BBString)
    <br />    
}

注意到 lambda 表达式中缺少 Emps 属性吗?这会为输入字段生成无效名称,并且默认模型绑定器在您回发时不会获取值。

我建议您使用编辑器模板而不是部分视图,如下所示:

<div id="mydiv">
    @using (Ajax.BeginForm("Index1", "Home", new AjaxOptions { UpdateTargetId = "mydiv", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" }))
    {        
        @Html.EditorFor(x => x.Emps)
        <input id="dosomething" type="submit" value="save" />
    }
</div>

然后在~/Views/SomeControllerName/EditorTemplates/Employee.cshtml 内:

@model Employee
@Html.TextBoxFor(x => x.Name)
@Html.TextBoxFor(x => x.Address)
@Html.ValidationMessageFor(x => x.BBString)
<br/>

将为Emps 集合的每个元素呈现编辑器模板,因此您无需编写任何循环。它将为输入字段生成正确的名称,以便默认模型绑定器能够在回发时填充值。编辑器模板位置很重要。它必须放在~/Views/Shared/EditorTemplates 内(如果您希望它在多个控制器之间重用)或在~/Views/SomeControllerName/EditorTemplates 内(如果您希望它仅在给定控制器的视图之间重用)。模板的名称也很重要。它应该被称为与集合的类型相同。因此,例如,如果您的视图模型中有一个公共属性 IEnumerable&lt;Employee&gt; Emps { get; set; },则必须将模板称为 Employee.cshtml,以便为该集合的每个元素自动呈现它。

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多