Model binding comma separated query string parameter

前端 未结 4 1767
逝去的感伤
逝去的感伤 2020-12-02 13:45

How can I bind query string parameter that is comma separated value

http://localhost/Action?ids=4783,5063,5305

to a controller action expec

4条回答
  •  忘掉有多难
    2020-12-02 13:59

    Taken from my answer:

    I will show you here a very simple custom model binder I have just written (and tested in .Net Core 2.0):

    My model binder:

    public class CustomModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var value = valueProviderResult.FirstValue; // get the value as string
    
            var model = value?.Split(",");
            bindingContext.Result = ModelBindingResult.Success(model);
    
            return Task.CompletedTask;
        }
    }
    

    My model (and notice, only one property has my custom model binder annotation):

    public class CreatePostViewModel
    {
        [Display(Name = nameof(ContentText))]
        [MinLength(10, ErrorMessage = ValidationErrors.MinLength)]
        public string ContentText { get; set; }
    
        [BindProperty(BinderType = typeof(CustomModelBinder))]
        public IEnumerable Categories { get; set; } // <<<<<< THIS IS WHAT YOU ARE INTERESTER IN
    
        #region View Data
        public string PageTitle { get; set; }
        public string TitlePlaceHolder { get; set; }
        #endregion
    }
    

    What it does is: it receives some text like "aaa,bbb,ccc", and converts it into array, and return it to the ViewModel.

    I hope that helps.

    DISCLAIMER: I am not an expert in model binders writing, I have learn that 15 minutes ago, and I found your question (with no helpful answer), so I tried to help. This is a very basic model binder, some improvements are surely required. I learned how to write it from the official documentation page.

提交回复
热议问题