Question

in a MVC application when you want to pass an id from the like this for example:

@if (Model.ImageData != null) { 
<div style="float:left; margin-right:20px">
    <img width="75" height="75" src="@Url.Action("GetImage",
    "Product", new {Model.ProductID})"/>

for a controller action method like this:

public FileContentResult GetImage(int productId)
{
    Product prod = repository.Products.FirstOrDefault
        (p => p.ProductID == productId);

    if (prod != null)
    {
        return File(prod.ImageData, prod.ImageMimeType);
    }
    else {
        return null;
    }
}

Why is it a must that it only works when I use anonymous new {Model.ProductID} ? When I try to pass the Model.ProductID as is given the Model is of type product, no Id is passed. How does this work?

Was it helpful?

Solution

Creating an anonymous class like new {Model.ProductID}

Will actually create the object like so:

new {ProductId = Model.ProductID}

Which Url.Action will write out as &ProductId=123

The default Model binder is case insensitive and will be able to map this to int productId signature of your GetImage controller method.

Whereas Model.ProductID will just be an integer - this is typically only mapped to id in a default MapRoute.

OTHER TIPS

ASP.NET MVC uses property names in anonymous objects or keys in RouteValueDictionary instances to match the values to route parameters. For example, the default route in ASP.NET MVC has 3 route parameters:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

If you don't tell the framework which parameter to to use, it will create an ambiguity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top