Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core custom model binder just for one property

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.

like image 449
Alex Avatar asked Jul 02 '17 12:07

Alex


People also ask

How does model binding work in asp net core application?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.

What is bind property?

Property binding moves a value in one direction, from a component's property into a target element property. For more information on listening for events, see Event binding. To read a target element property or call one of its methods, see the API reference for ViewChild and ContentChild.

In which of the following places will the default model binder look in order to build an object passed as a parameter to an MVC 5 controller method?

The MVC runtime uses Default ModelBinder to build the model parameters. This is done automatically by MVC Model Binder. Let us understand by a simple example how model information is passed to the controller by model binding from view in MVC.


1 Answers

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.

like image 60
Mohammed Noureldin Avatar answered Oct 05 '22 04:10

Mohammed Noureldin