如何将实体键(引用)从视图传递给控制器

时间:2009-06-01 19:21:15

标签: asp.net-mvc linq-to-entities

我有一个带linq到sql的工作页面,现在我正在将它转换成linq到实体

我的测试项目包含2个表,联系人(ID,姓名,电子邮件)和评论(id,contactid,comment)

当我想创建一个新评论时,我在隐藏字段中放入了视图中的contactid,并且在提交按钮上提交了其他所有内容

它与linq2sql一起工作正常,但它不适用于linq2entity

如何使用linq2entity做到这一点?

编辑#1

事实上问题是,我如何处理一个或多个外键?在这种情况下,我只有一个,是的,我可以使用 eu-ge-ne 的建议,但如果我得到第二个呢?

编辑#2

现在

found this解决方案

1 个答案:

答案 0 :(得分:1)

最好将contactId作为url的一部分提供。例如(使用“默认”路线):

public CommentController : Controller
{
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Add(int id)
    {
        ...
    }
}

在您的视图中:

<% using (Html.BeginForm(new {
    controller = "comment",
    action = "add",
    id = /* commentId from your Model */ })) { %>
    ...
<% } %>

<强>更新:

如果您有2个或更多外键:

<强> S1:

routes.MapRoute("CustomRoute", "{controller}/{action}/{id1}/{id2}",
    new { controller = "home", action = "index", id1 = "", id2 = "" });

...

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id1, int id2)
{
    ...
}

...

<% using (Html.BeginForm(new {
    controller = "comment",
    action = "add",
    id1 = /* foreighn key 1 */,
    id2 = /* foreighn key 2 */ })) { %>
    ...
<% } %>

<强> S2:

在视图中:

<% using (Html.BeginForm(new { controller = "comment", action = "add" })) { %>
    ...

    <input id="foreignKeyId1" type="hidden" value="<%= /* foreign key 1 */ %>" />
    <input id="foreignKeyId2" type="hidden" value="<%= /* foreign key 2 */ %>" />
    ...
    <input id="foreignKeyIdN" type="hidden" value="<%= /* foreign key N */ %>" />
<% } %>

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(FormCollection form)
{
    var foreignKey1 = form["foreignKeyId1"]
    var foreignKey2 = form["foreignKeyId2"]
    ...
    var foreignKeyN = form["foreignKeyIdN"]

    ...
}