简体   繁体   中英

null values sent by jQuery.ajax() are bound to “null” fields in the model

I want my model's part to be accessible to my page's JavaScript, so I include the following script tag into the model:

<script type="text/javascript">
var filter = @Html.Raw(@Json.Encode(Model.Filter));
</script>

The filter object is a filter for the subsequent queries, which are done via AJAX:

<script type="text/javascript">
function DownloadData() {
    $.ajax({
        url: '@Url.Action("GetData")',
        type: "POST",
        data: filter,
        success: function (data) {
        }
    });
}
</script>

It all works OK, but for one part: the filter 's string properties are not null , but "null" . I don't touch the filter variable in my JavaScript yet

Model:

public class SellOffersFilter
{
    public int MinAge { get; set; }
    public string Country { get; set; }
    public string City { get; set; }
}

Controller:

public ActionResult SellOffersGetPage(SellOffersFilter filter)
{
    //here both filter.Country and filter.City are equal to "null"
}

The POST form looks like MinAge=0&Country=null&City=null , and JavaScript debugger shows that filter.Country is equal to null , not the "null" string.

Is there a way to force jQuery not to pack the filter's fields into the POST request, if they are null ? Or another easy way to pass null values through jQuery.ajax() ?

This is most definitely something you should do on your server, not on the client.

Making the client not use "null" by mistake doesn't mean the client can't do a request with null values.

The whole AJAX concept falls short of proper validation, where people are pushing validation to the client-side level. This is wrong. It means there will be more hidden server bugs in the future (for all kinds of hackers to exploit).

I didn't figure out the answer, so I had to manually replace null values with empty strings on the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM