views:

49

answers:

2

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.

A: 

I think you should first get an instance of the attendee class from repository before you call Save function.

var attendeeToEdit=repository.GetAttendee(attendee.ID);
UpdateModel(attendeeToEdit);

I'm guessing something like that may work. Try it and see if it works.

Ufuk Hacıoğulları
Tried it, no avail.
toccig
Do any of the values in model change?
Ufuk Hacıoğulları
Your solution was correct in part. I also needed to change the ValueProvider for UpdateModel(). Thanks for your help!
toccig
no problem (is it 15 chars yet?)
Ufuk Hacıoğulları
15 chars? is that like 5pm?
toccig
A comment has to be at least 15 chars. I was spamming
Ufuk Hacıoğulları
+1  A: 

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.

toccig