0

Given the following code:

Models

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

View

<%@ 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

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

[HttpPost]
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?

3
  • 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,. Commented Oct 13, 2009 at 15:37
  • I doubt this is an HTTP issue. Commented Oct 13, 2009 at 15:39
  • 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). Commented Oct 13, 2009 at 15:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tested without the <%= Html.DisplayFor(log => log.Ticket) %> and it is still null.
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 %>" />.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.