Reputation: 20140
I had a working page with linq to sql and now I'm currently converting it into linq to entity
My test project contain 2 tables, contact(id,name,email) and comments(id,contactid,comment)
when I want to create a new comment, I put in the view in a hidden field the contactid and it was submitting with everything else on the submit button
it was working fine with linq2sql but it doesn't work with linq2entity
how to do that with linq2entity?
edit #1
in fact the question is, how do I deal with one or many foreign key? in that case, I only got one and yes I could use the suggestion from eu-ge-ne but what if I got a second one?
edit #2
found this solution for now
Upvotes: 0
Views: 278
Reputation: 28153
It is better to provide the contactId as a part of url. For example (with "Default" route):
public CommentController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id)
{
...
}
}
In your View:
<% using (Html.BeginForm(new {
controller = "comment",
action = "add",
id = /* commentId from your Model */ })) { %>
...
<% } %>
UPDATED:
If you have 2 or more foreign keys:
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:
In the View:
<% 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"]
...
}
Upvotes: 1