简体   繁体   中英

unable to get parameter value in controller which is passed from the url

I want to pass dynamic values to the controller like querystring. I am passing a string but im getting null in the controller. I am hitting the url " http://localhost:62666/tracker/MapDetails/sss " but not getting any value in the controller. Can you point out where I made a mistake?

Controller:

public ActionResult MapDetails(string val)
{
    AssetTracker model = new AssetTracker();
    model.deviceid = val;
    return View(model);
}

View:

@model smartpond.Controllers.AssetTracker
@{
    ViewBag.Title = "MapDetails";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>
    My device id is : @Model.deviceid
</h1>

You get Null value in the controller because the model binder in MVC couldn't bind the variable you've passed to the MVC routes So, you need to add your custom route that meets your passing parameters to identify them to the model binder to add your custom routes, you have to write it in the RouteConfig.cs File in the app_start folder in your solution and make sure that you append it at the top of the default route with a different name.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM