views:

1643

answers:

3
+2  Q: 

MVC Update Model

I'm unsure if this has been asked before but here goes.

I have an MVC application with the HTML looking like this;

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<EnvironmentalVandals.Controllers.MonthlyItemsFormViewModel>" %>

I have in the controller the following;

    [Authorize]
    public ActionResult Edit(int? id)
    { snip }

Then on a submit button event;

    [AcceptVerbs(HttpVerbs.Post)]
    [Authorize]
    public ActionResult Edit(FormCollection collection)
    {
        CalendarItem fvm = new CalendarItem();

        UpdateModel(fvm);
    }

If I am updating an existing event I have no problems. If I am adding a new event I get an error that UpdateModel failed to update the model.

If I remove the "int? id" parameter from the first ActionResult the model is updated on both new and existing events.

When I am editing an event I use the following HTML; <%=Html.ActionLink("Edit", "Edit", new {id=Model.Event.id}) %> and when I am creating a new event I use <%=Html.ActionLink("Add event","Edit", "Calendar") %>.

Now admitably I probably shouldn't be using the same View for both update and create and should perhaps refactor into two views and a PartialView.

So, is that the solution or is there something else I am doing wrong?

Thanks in advance.

</griegs>

A: 

I can't see the rest of your code, but I am assuming that on an edit you are passing an existing record into the view. When you try to post a new record with the same ID, the controller thinks you are trying to modify the existing record instead of creating a new one.

I think you can use the same view for both edits and adds, but on an add you will have to pass in a newly'created record object to your view. For my money it's easier to post to two different controller methods (one for add, one for edit), and do the grunt work there.

Robert Harvey
Yeah the rest of the code is a little dull but like you say. I have tried passing in a newly created object and I have tried filling that object with dummy data incase I missed a non nullable field somewhere. Still no joy.The issue [only] happens when I try to UpdateModel on a postback from the submit button.
+2  A: 

OK, turns out you really should have seperation of concerns.

I created Add and Edit actions, converted the edit screen into a partial view and added an Add view.

All works perfectly.

I guess with regards to mvc the following is true. "When it becomes hard you're probably doing it wrong".

A: 

I think the answer you can find here http://www.asp.net/mvc/videos/aspnet-mvc-how-10-minute-technical-video-for-developers

Sedgar