Persisting Properties in Models in ASP.NET MVC (with Binder?)

Given the following code:


class Log
   Ticket Ticket { get; set; }
   string Message { get; set; }
class Ticket
   Importance Importance { get; set; }
   string Name { get; set; }


<%@ Language="C#" Inherits="System.Web.Mvc.ViewPage<Models.Log>" %>
<%= Html.DisplayFor(l => l.Ticket.Name) %>
<%= Html.EditorFor(l => l.Message) %>
<%= Html.EditorFor(l => l.Ticket.Importance) %>

Controller Actions

public ActionResult Update(int id)
    Ticket t = _tickets.Get(id);
    return View(new Log { Ticket = t });

public ActionResult Update(Log l)
   // My problem is here:
    l.Ticket.Name; // This is null
    l.Ticket.Importance; // while this one is still set

Is there any way to persist the Ticket in the Log that is passed?

13.10.2009 15:28:54
You could probably just store the ticket name in a hidden field, but more reasonably you might want to consider simply accepting the way http works rather than fighting it,.
meandmycode 13.10.2009 15:37:18
I doubt this is an HTTP issue.
Daniel A. White 13.10.2009 15:39:28
It is.. because you aren't sending a Ticket back in the form.. you are sending the importance property and the message property of the log.. it is factually that what you send to the view ISN'T what is sent BACK in the postback.. it is a subset (purposely so).
meandmycode 13.10.2009 15:49:19

Name will be output for display as plain text, meaning that there wont be a variable passed back to your page as part of your post as it isnt part of a form. Workarounds are to put it in a hidden field or lookup your model as part of your Update method then call UpdateModel on the retrieved item.

13.10.2009 15:41:27
I tested without the <%= Html.DisplayFor(log => log.Ticket) %> and it is still null.
Daniel A. White 13.10.2009 15:43:04
You need to add hidden field, not to remove label. Try Html.Hidden(l => l.Ticket.Name) (syntax depend on MVC v2) or smth like <input type="hidden" name="Ticket.Hidden" value="<%= Model.Ticket.Name %>" />.
queen3 13.10.2009 17:53:20