Here is a common scenario
I Have these Entity
User
UserId
UserName
…
UserQuestion
UserQID
UserID
UserQuestion
UserAnswer
One user can Have many question, but one question is attached to one user.
In my example, I create 3 Empty entities (UserQuestion). Then I attache these question on the user.
In the view, for each question, answer textbox, I Use ElementAt to specify each of the UserQuestion Entity.
Why I cannot save these 3 questions
In the Controller
public ActionResult ChooseQuestion()
{
IUserRepository repUser = new UserRepository(EntityFactory.GetEntity());
User usr = repUser.GetUserByID(Convert.ToInt32(Session["UserID"]));
usr.UserQuestions.Add(new UserQuestion());
usr.UserQuestions.Add(new UserQuestion());
usr.UserQuestions.Add(new UserQuestion());
var ViewModel = new UsrViewModel()
{
UserInfo = usr
};
return View(ViewModel);
}
[HttpPost]
public void ChooseQuestion(User UserInfo)
{
UpdateModel(User, "UserInfo");
EntityFactory.GetEntity().SaveChanges();
}
In my View
<%: Html.TextBoxFor(model => model.UserInfo.UserName)%>
...
<%: Html.TextBoxFor(model => model.UserInfo.LastName%>
...
<%: Html.TextBoxFor(model => model.UserInfo.UserPassword%>
..
<h2>Question Creation</h2>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(0).UserQuestion)%>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(0).UserAnswer)%>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(1).UserQuestion)%>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(1).UserAnswer)%>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(2).UserQuestion)%>
<%: Html.TextBoxFor(model => model.UserInfo.UserQuestions.ElementAt(2).UserAnswer)%>
3
Based on Phil Haack’s post you should just have sequential number in your name attribute like so:
Normally the built-in HtmlHelper.TextboxFor method will do the name attribute correctly if it is in a for loop.
As I’m not near my VS now I can’t try this magic out for myself, but you might want to check Phil’s article if you get stuck.