简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM