2

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()?

2 Answers 2

1

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).

Sign up to request clarification or add additional context in comments.

4 Comments

I don't understand how this is relevant to my question. I'm not talking about validation at all. All I want is that null values are not turned into "null" strings on the request.
A request is a string. A null value can be represented in different ways, but equal to none. It could mean "null", "" (empty) as well as %00 (null character).
Thank you for your time, but this doesn't answer my question at all
Zruty - It answers your question well. It's just you that don't want to bother putting 1+1...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.