0

我在 ASP.NET MVC 应用程序中使用 Linq to SQL。该模型由一个带有指向选项表的外键链接的决策表组成(一个决策,许多选项)。因此,模型允许我通过 Decision.Options 属性访问 Options 集合。我想允许我的用户在更新其他决策属性的单独视图中更新决策的选项集合。将 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 });
     }

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

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

我已经让它用于直接编辑决策对象,但是在使用模型绑定器或 FormCollection 更新模型中的子表时遇到问题。任何帮助是极大的赞赏!

4

1 回答 1

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 关于该主题的博客条目。

于 2009-07-11T15:14:34.500 回答