Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a simple model for my asp.net core controller:

[HttpPost]
public async Task<DefaultResponse> AddCourse([FromBody]CourseDto dto)
{
     var response = await _courseService.AddCourse(dto);
     return response;
}

My model is :

 public class CourseDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Genre { get; set; }
    public string Duration { get; set; }
    public string Level { get; set; }
    public string AgeRange { get; set; }
    public string Notes { get; set; }
    public bool Active { get; set; }
    public string OrganisationCode { get; set; }
}

I'm trying to set value of "OrganisationCode" using a custom mode binder or action filter, but had no success. I would be thnakful if you advise whats the right way to updat ethe model before executing the action.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
686 views
Welcome To Ask or Share your Answers For Others

1 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<string> 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 learnt 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...