I'm and MVC1 programmer, new to the MVC2.
The data will not persist to the database in an edit scenario. Create works fine.
Controller:
//
// POST: /Attendee/Edit/5
[Authorize(Roles = "Admin")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Attendee attendee)
{
if (ModelState.IsValid)
{
UpdateModel(attendee, "Attendee");
repository.Save();
return RedirectToAction("Details", attendee);
}
else
{
return View(attendee);
}
}
Model:
[MetadataType(typeof(Attendee_Validation))]
public partial class Attendee
{
}
public class Attendee_Validation
{
[HiddenInput(DisplayValue = false)]
public int attendee_id { get; set; }
[HiddenInput(DisplayValue = false)]
public int attendee_pin { get; set; }
[Required(ErrorMessage = "* required")]
[StringLength(50, ErrorMessage = "* Must be under 50 characters")]
public string attendee_fname { get; set; }
[StringLength(50, ErrorMessage = "* Must be under 50 characters")]
public string attendee_mname { get; set; }
}
I tried to add [Bind(Exclude="attendee_id")] above the Class declaration, but then the value of the attendee_id attribute is set to '0'.
View (Strongly-Typed):
<% using (Html.BeginForm()) {%>
...
<%=Html.Hidden("attendee_id", Model.attendee_id) %>
...
<%=Html.SubmitButton("btnSubmit", 开发者_开发知识库"Save") %>
<% } %>
Basically, the repository.Save(); function seems to do nothing. I imagine it has something to do with a primary key constraint violation. But I'm not getting any errors from SQL Server. The application appears to runs fine, but the data is never persisted to the Database.
Got It! Here's the solution:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection form)
{
Attendee attendee = repository.GetAttendee(id);
try
{
UpdateModel(attendee, form);
repository.Save();
return RedirectToAction("Details", attendee);
}
catch
{
return View(attendee);
}
}
The UpdateModel() ValueProvider was the problem.
精彩评论