I have a person table which has two properties: ID, nameID; And a personName table which has four properties: NameID, Firstname, Middlename, Lastname; Here nameID is a foreign key form PersonName table to PersonTable; (Hope you understand i am here to test the multi valued attribute test.)
Then i made a ADO.net datamodel of these two tables. After that i made a custom shape model called NameViewData which looks like:
public class NameViewData
{
public Person Person { get; set; }
public PersonName Name { get; set; }
public NameViewData(Person person, PersonName personName)
{
Person = person;
Name = personName;
}
}
I created a name controller where i wish to use CRUD operations. In this controller i wrote the Edit action(GET Method) like this:
public ActionResult Edit(int id)
{
Person person = db.Person.First(x=>x.Id == id);
PersonName personName = db.PersonName.First(x=>x.NameId == id);
return View(new NameViewData(person, personName));
}
Now the problem is that i am not sure how to write the Edit action (POST method) and the Edit View page. I wrote like this:
Edit View:
Inherits="System.Web.Mvc.ViewPage<Name.Models.NameViewData>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Name.Firstname">Firstname:</label>
<%= Html.TextBox("Name.Firstname", Model.Name.Firstname)%>
<%= Html.ValidationMessage("Name.Firstname", "*")%>
</p>
<p>
<label for="Name.Middlename">Middlename:</label>
<%= Html.TextBox("Name.Middlename", Model.Name.Middlename)%>
<%= Html.ValidationMessage("Name.Middlename", "*")%>
</p>
<p>
<label for="Name.Lastname">Lastname:</label>
<%= Html.TextBox("Name.Lastname", Model.Name.Lastname)%>
<%= Html.ValidationMessage("Name.Lastname", "*")%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
Edit POST:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
Person person = db.Person.First(x=>x.Id == id);
PersonName personName = db.PersonName.First(x=>x.NameId == id);
NameViewData nameViewData = new NameViewData(person, personName);
try
{
TryUpdateModel(nameViewData);
if (ModelState.IsValid)
{
db.AddToPersonName(nameViewData.Name);
db.AddToPerson(nameViewData.Person);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
But this not working. Can you please help me out. And also what should i read about custom shape view model, provide any link if possible.