Asp.net mvc 如何将entitykey(引用)从视图传递到控制器
我有一个使用LINQtoSQL的工作页面,现在我正在将其转换为LINQtoEntity 我的测试项目包含两个表,联系人(id、姓名、电子邮件)和备注(id、contactid、备注) 当我想创建一个新的评论时,我在视图中的一个隐藏字段中放置了contactid,它与submit按钮上的其他内容一起提交 它在使用linq2sql时运行良好,但在使用linq2sql时不起作用 如何使用LINQ2实体实现这一点 编辑#1 事实上,问题是,如何处理一个或多个外键?在这种情况下,我只得到了一个,是的,我可以使用欧盟ge ne的建议,但是如果我得到第二个呢 编辑#2Asp.net mvc 如何将entitykey(引用)从视图传递到控制器,asp.net-mvc,linq-to-entities,Asp.net Mvc,Linq To Entities,我有一个使用LINQtoSQL的工作页面,现在我正在将其转换为LINQtoEntity 我的测试项目包含两个表,联系人(id、姓名、电子邮件)和备注(id、contactid、备注) 当我想创建一个新的评论时,我在视图中的一个隐藏字段中放置了contactid,它与submit按钮上的其他内容一起提交 它在使用linq2sql时运行良好,但在使用linq2sql时不起作用 如何使用LINQ2实体实现这一点 编辑#1 事实上,问题是,如何处理一个或多个外键?在这种情况下,我只得到了一个,是的,我可
目前的解决方案最好将contactId作为url的一部分提供。例如(使用“默认”路线): 在你看来:
<% using (Html.BeginForm(new {
controller = "comment",
action = "add",
id = /* commentId from your Model */ })) { %>
...
<% } %>
...
更新:
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 */ })) { %>
...
<% } %>
如果您有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 */ })) { %>
...
<% } %>
routes.MapRoute(“CustomRoute”、“{controller}/{action}/{id1}/{id2}”,
新的{controller=“home”,action=“index”,id1=“”,id2=“”});
...
[接受动词(HttpVerbs.Post)]
公共行动结果添加(int id1,int id2)
{
...
}
...
...
S2:
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 */ })) { %>
...
<% } %>
他认为:
<% 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"]
...
}
...
...
[接受动词(HttpVerbs.Post)]
公共行动结果添加(FormCollection表单)
{
var foreignKey1=表格[“foreignKeyId1”]
var foreignKey2=表格[“foreignKeyId2”]
...
var foreignKeyN=表格[“foreignKeyIdN”]
...
}
在我的原始帖子中查看我的编辑,如果我只有一个外键,这是个好主意,但是如果我有多个外键呢?