How to access fields in view with different ASP.NET MVC type

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) { ... }

      

representation

// 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"), it knownLocation

works fine. In Edit ("B"), knownLocation

throws an exception (behind the scenes):

Parameter dictionary contains null for parameter "knownLocation" of non-nullable type "System.Int32" for method "System.Web.Mvc.ActionResult Modify (TechHelp.Core.Models.Log, Int32, System.String, Int32, System.String) 'to' TechHelp.Mvc.Controllers.TicketsController The optional parameter must be a reference type, a nullable type, or declared as an optional parameter.

How can I access this field? Note that it cannot bind to the Model property.

+2


source to share


1 answer


If you look at the generated html you have to make sure that the name of the input being generated is different in each case.

If you really want to get the result straight from the POST, you need to make sure your int knownLocation matches the input name that is generated in the second case (I suspect it is Ticket_KnownLocation, but I will also assume that you are using an MVC 2 pre-build, so for you it may be different).



Regardless, I'd say you probably don't want to pull the knownLocation directly from the POST. If the Controller needs to access it, I would really suggest making it public in the Model and letting the ModelBinding framework do your work for you. Then you access it with log.Ticket.KnownLocation.

+2


source







All Articles