1

I want to get the id's of all selected items, but I only get the first one in the action in the controller. I expected the values to come as a comma-separated list, but no.

Code:

@foreach (ICulture cult in await _genRepo.GetCulturesAsync())
{
    <label>
        <input type="checkbox" name="lang" id="lang" value="@cult.Id" /> @cult.DisplayName
    </label>
}

Controller action method:

[HttpPost("siteAPI/SaveSiteLanguageAsync")]
public async Task<IActionResult> SaveSiteLanguageAsync([FromForm] Guid app, [FromForm] string lang) 
{
    ...
}
0

1 Answer 1

2

If you want to accept a list, you can just use a array or a list to accept it

[HttpPost("siteAPI/SaveSiteLanguageAsync")]
public async Task<IActionResult> SaveSiteLanguageAsync([FromForm] Guid app, [FromForm] 
string[] lang) 
{
   ...
}

And if you want to accept a comma-separated string, you can use custom model binding.

Below is an example:

LangBinder:

public class LangBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var langs = bindingContext.ValueProvider.GetValue("lang");

        if (langs == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        string langlist = string.Join(",", langs);
        
        bindingContext.Result = ModelBindingResult.Success(langlist);
        return Task.CompletedTask;
    }
}

Controller action:

[HttpPost("siteAPI/SaveSiteLanguageAsync")]
public async Task<IActionResult> SaveSiteLanguageAsync([FromForm] Guid app, [ModelBinder(typeof(LangBinder))] string lang) 
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.