skip to Main Content

In the below code I am passing an empty value for "FirstName". When the Ajax POST request is made on the controller side the "FirstName" parameter value is coming as Null but if I pass any value the value is binded to the parameter. Only for the empty values, the value is showing as null in asp.Net core project

Javascript:

var dataVal = {};
dataVal["FirstName"] = "";

$.ajax({
    type: "POST",
    "url":url,
    data:dataVal,
    dataType: "json",
    async: false,
    success: function (m) {
        if(m){
            alert(m);
        }
    
    },
    error: function(err){
    
    }
});

Controller:

public IActionResult Home(string FirstName){


}

2

Answers


  1. Do you want to receive "" instead of null in controller when ajax send request with the value of FirstName is ""?

    The explation about this is as follows:

    This is simply because MVC 2.0 defaults to initializing strings to null. To be more precise, if an empty string means has no value, So .NET sets the default value of its. And the default string (belonging to reference type) is null. So The ModelBinder sets the properties to their default value if no value is provided in the request.

    refer to this link.

    Attention: link provided above is about Asp.net MVC, There are some methods do not work in .Net Core. For example, Someone provided a method to change bindingContext.ModelMetadata.ConvertEmptyStringToNull = false; to receive "" in controller, But in asp.net core’s document:

    Gets a value indicating whether or not to convert an empty string
    value or one containing only whitespace characters to null when
    representing a model as text.

    public abstract bool ConvertEmptyStringToNull { get; }

    ConvertEmptyStringToNull just has a get method, So you can’t change it.

    Login or Signup to reply.
  2. Use the [HttpPost] attribute on the above action method and set the default value to string parameter. The below code for reference:

    [HttpPost]
    public IActionResult Home(string FirstName="")
    {
        …
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search