Frage

I have definded this rule:

routes.MapRoute(
    name: "NameOfRule",
    url: "general-list/all-operation/{typeEstate}/{page}",
    defaults: new { controller = "PropertyListings", action = "Sale", page = UrlParameter.Optional },
    namespaces: new[] { ControllerName.Namespace }
);

public ActionResult Sale(string typeEstate, int page)
{
    //...
}

this works fine if I pass the parameter page, but if I don't this fails, and the error is "you need page or it has to be null (int?)"

I don't understand because I'm assuming that the parameter page is optional. Of course, if I get a class change and this works correctly:

public class MyModel
{
    public string TypeEstate { get; set; }

    public int Page { get; set; }
}

public ActionResult Sale(MyModel model) //string typeEstate, int page)
{
   //...
}
War es hilfreich?

Lösung

It is optional as far as the route and route matching is concerned. However, if you do not allow a null value for that parameter into your function, then the function is going to dictate that that particular value cannot be null. So, if that value does not exist, the route will match, but because the function is not setup to take a null (or optional value such as int id = 0), then it will fail with a null reference exception.

As to why passing it in as a class works, that is because the default value of an uninitialized integer is 0 (however, a int? default value is null). So, it has a value even though you never gave it one just from being "newed" up.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top