用于更新子表的ASP.NET模型绑定器问题

时间:2009-07-11 14:48:59

标签: asp.net-mvc linq-to-sql updatemodel

我在ASP.NET MVC应用程序中使用Linq to SQL。该模型包含一个Decisions表,其中包含指向Options表的外键链接(一个决策,多个选项)。因此,Model允许我通过Decision.Options属性访问Options集合。我想允许我的用户在单独的视图中更新Decision的Options集合,以更新其他Decision属性。将Options集合传递回控制器以更新Decision对象的最佳方法是什么?这是代码:

控制器将决策模型发送到选项视图:

   //
    // GET /Decisions/Options/5
     [Authorize]
     public ActionResult Options(int id)
     {
         Decision decision = decisionRepository.GetDecision(id);
         return View(decision);
     }

我的视图页面只列出了用户修改和提交的选项名称字段:

<% using (Html.BeginForm())
{%>
    <div id="answers">
        <table>
        <% int i = 0; %>  
        <% foreach (var item in Model.Options)
           { i += 1;
         %>
            <tr>
                <td>
                    <label>Option #<%= i%>:&nbsp;&nbsp;</label>
                    <%= Html.TextBox("Option.Name", item.Name)%>
                </td>
            </tr>

        <% } %>
        </table>

        <input type="submit" name="button" value="Back" />
        <input type="submit" name="button" value="Next" />
    </div>
    <% } %>

以下是Options POST操作的控制器代码:

     // POST /Decisions/Options/4
     [AcceptVerbs(HttpVerbs.Post), Authorize]
     public ActionResult Options(int id, string button, Decision d)
     {
         Decision decision = decisionRepository.GetDecision(id);

         if (decision == null)
             return View("NotFound");

         if (button == "Back")
         {
             return RedirectToAction("Edit", new { id = decision.DecisionID });
         }

         //Update the options in the decision model             
         //TODO: What's the best way to update the Decision.Options parameter?

         //Save options and move on to factors
         UpdateModel(decision);
         decisionRepository.Save();
         return RedirectToAction("Factors", new { id = decision.DecisionID });
     }

在Options的POST操作中,传回Option项集合的最佳方法是什么?

在调用Save方法之前,我已尝试直接使用FormCollection转换为EntitySet以分配给Decision.Options。上面的代码传入了Decision对象,但是Options集合始终为null,因此我的注释为TODO。

我已经将其用于直接编辑Decision对象,但是在使用Model Binder或FormCollection更新模型中的子表时遇到了问题。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

由于您有许多潜在的选择,您需要区分每个输入与其他输入。你不能给他们所有相同的名字。

而不是:

 <%= Html.TextBox("Option.Name", item.Name)%>

尝试使用:

  <%= Html.TextBox("Option[" + i + "].Name", item.Name)%>

然后在您的操作中将Option数组作为参数之一。

public ActionResult Options(int id,string button,Decision d,Options [] options)    {       ...    }

然后,您可以执行将提供的选项连接到决策所需的操作。

请参阅Hanselman关于该主题的blog条目。

相关问题