Saeid Mirzaei
Saeid Mirzaei

Reputation: 1236

Map route parameters to model in asp.net core

I have an action with the following annotation,

[HttpGet("update/{hash}")]
public async Task<IActionResult> Update([FromQuery]Model model)
{
    // I need to use from model.Hash
    return Ok();
}

In addition, I have a simple model like below:

public class Model
{
    public string Hash { get; set; }
}

The model binder is not working, because that's clear the hash is not a queryString like ?hash=[value], it's an id.

I can not use another parameter to bind it like:

public async Task<IActionResult> Update(string hash)

because I have a validator for my model.

Is there any way in which I can bind hash to Hash my property?

Upvotes: 4

Views: 3015

Answers (2)

MarredCheese
MarredCheese

Reputation: 20791

Don't use [FromQuery] if you aren't getting anything from the query.

You can replace that attribute with [FromRoute].

If you change {hash} to {Hash} in the route pattern, you can leave Model alone instead of having to add an attribute to it to override the name to lowercase.

[HttpGet("update/{Hash}")]
public async Task<IActionResult> Update([FromRoute]Model model)
{
    return Ok();
}

public class Model
{
    public string Hash { get; set; }
}

Upvotes: 1

Balagurunathan Marimuthu
Balagurunathan Marimuthu

Reputation: 2978

You can able to bind the route parameter to the model property by using [FromRoute(Name = "hash")] as shown in below.

public class Model
{
   [FromRoute(Name = "hash")]
   public string Hash { get; set; }
}

Refer this Microsoft doc

Upvotes: 4

Related Questions