KevinBui
KevinBui

Reputation: 1099

Context.Request.Query["id"] return null in View

I want to get "id" parameter in View, but Context.Request.Query["id"] return null value.

Query like this:localhost:1000/MyController/Getuser/65190907-1145-7049-9baa-d68d44b1ad06

// Controller
public ActionResult Getuser(Guid id)
{
    //HttpContext.Request.Query["id"] also return null
    return View();
}

//in startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Upvotes: 1

Views: 2563

Answers (2)

KevinBui
KevinBui

Reputation: 1099

I think I can get it by ViewContext.ModelState["id"].AttemptedValue

Upvotes: 2

CodeFuller
CodeFuller

Reputation: 31282

Request.Query contains query string of the request, i.e. URL part that goes after question mark: ...?param1=value1&param2=value2. URL localhost:1000/MyController/Getuser/65190907-1145-7049-9baa-d68d44b1ad06 does not contain query string. GUID 65190907-1145-7049-9baa-d68d44b1ad06 is just a part of URL path.

If for some reason you want to access id parameter from raw request, not via Model Binding, you have two options:

  1. Pass id in query string and access it via HttpContext.Request.Query["id"]:

    In this case request URL will be http://localhost:1000/MyController/Getuser?id=65190907-1145-7049-9baa-d68d44b1ad06. No changes in routes are required.

  2. The second option is to extract id from Request.Path:

    public IActionResult Getuser(Guid id)
    {
        var path = HttpContext.Request.Path;
        var id2 = Guid.Parse(path.Value.Split('/').Last());
    
        return View();
    }
    

Upvotes: 1

Related Questions