Search code examples
asp.net-mvcrazorasp.net-mvc-5

Why ViewContext.RouteData.Values["X"] return key vlaue ? while I expect just the value


I expect in Razor the @ViewContext.RouteData.Values["id"] return an integer , While it return 'Id=X'.

for instance my controller like :

public ActionResult Index(int? id)
 {
     return View();
 }

And in Razor :

<input type="text" value='@ViewContext.RouteData.Values["id"]' id="routeDataId" />

the result is a Textbox with the value of 'Id=X'


Solution

  • I expect in Razor the @ViewContext.RouteData.Values["id"] return an integer , While it return Id=X.

    Returning Id=X by RouteData.Values["id"] is correct behaviour, according to MSDN.

    If you want to get a value of that object, you could use:

    @ViewContext.RouteData.Values["id"].ToString()
    

    So, your input should look like:

    <input type="text" value='@ViewContext.RouteData.Values["id"].ToString()' id="routeDataId" />
    

    If this also won't work, you could do that trick:

    public ActionResult Index(int? id)
     {
         if(id.HasValue)
            TempData["id"] = id;
         else
            TempData["id"] = "empty value";
    
         return View();
     }
    

    and then:

    <input type="text" value='@TempData["id"]' id="routeDataId" />