How to access fields in View with different type ASP.NET MVC
Given the following code
Action methods
// Action for A
public ActionResult New(Ticket t, int knownLocation, string location) { ... }
// Action for B
public ActionResult Edit(Log log, int id, string assignTo, int knownLocation, string location) { ... }
Views
// Ticket.ascx
<%= Html.EditorFor(t => t.KnownLocation);
// A
<%@ Inherits="System.Web.Mvc.ViewPage<Models.Ticket>" %>
<%= Html.EditorForModel() %>
// B
<%@ Inherits="System.Web.Mvc.ViewPage<Models.Log>" %>
<%= Html.EditorFor(l => l.Ticket) %>
Model
class Log
{
...
Ticket Ticket { get; set; }
string Message { get; set; }
...
}
class Ticket
{
...
Importance Importance { get; set; }
string Name { get; set; }
// Please note the protected access level
Location KnownLocation { get; protected set; }
string Location { get; protected set; }
...
}
In New ("A"), knownLocation
works fine. In Edit ("B"), knownLocation
throws an exception (behind the scenes):
The parameters dictionary contains a null entry for parameter 'knownLocation' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(TechHelp.Core.Models.Log, Int32, System.String, Int32, System.String)' in 'TechHelp.Mvc.Controllers.TicketsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
How can I access that field? Note that it can't bind to the Model's property.
If you look at the html that's being created, you ought to see that the name of the input that's being created is different in each case.
If you really want to grab the result straight out of the POST then you'll need to make sure that your int knownLocation matches the name of the input that's being created in the second case (I suspect it's Ticket_KnownLocation, but I also suspect you're using an MVC 2 preview build, so it might be different for you).
Regardless, I'd say that you probably don't want to be pulling knownLocation straight out of the POST. If the Controller needs access to it, I'd really advise making it public on the Model and letthing the ModelBinding framework do your work for you. You then access it with log.Ticket.KnownLocation.
链接地址: http://www.djcxy.com/p/39206.html上一篇: 验证级联下拉列表