How to ignore empty values when passing a ViewModel (object) via Ajax to an MVC controller

可紊 提交于 2019-12-13 07:03:55

问题


In the following view I'm passing an Object (ViewModel) to controller. It works fine if user enters all the values in the form. The sample Requested URL with querystring generated via LINQ query is as follows:

Request URL:http://localhost:50507/OrdCtrl/OrdAction?OrdYear=2016&OrderNumber=CE123&OrderName=testOrder&hasOrdered=true&_=1489509308855

But if the user skips entering one value in the search form, say, orderName the user gets the expected error:

NullReferenceException: Object reference not set to an instance of an object.

I think the above error occurs since the generated Requested URL is missing the parameter value for orderName as shown below:

Request URL:http://localhost:50507/OrdCtrl/OrdAction?OrdYear=2016&OrderNumber=CE123&OrderName=&hasOrdered=true&_=1489509308855

Question: In the dataObj inside Ajax call below, how can we skip the input parameters if their values are empty strings - so the generated querystring does not include those parameters. NOTE: This is a search form and users are allowed to search based only on the values they enter inside form.

TestViewModel:

public class UsetListViewModel
{
    public int OrdYear { get; set; }
    public string OrderNumber { get; set; }
    public string OrderName { get; set; }
    public bool hasOrdered { get; set; }
}

View:

@model TestProj.Models.TestViewModel

....<!--Some html here-->

<div>
    <form asp-controller="OrdCtrl" asp-action="OrdAction" method="get">
        <input type="hidden" asp-for="OrdID" />
        <div ><button type="button" id="SearchBtn">Search</button></div>
    </form>
</div>
<div id="searchResults"></div>     


@section scripts
{
    <script>
        $(document).ready(function () {

            $('#SearchView').on('click', '#SearchBtn', function (event) {

                var dataObj = {
                    OrdYear: $('#yearID').val(),
                    OrderNumber: $('#OrdNumb').val(),
                    OrderName: $('#OrdName').val(),
                    hasOrdered : $('[name=hasOrd]:checked').val()
                }

                $.ajax({
                    url: '@Url.Action("OrdAction", "OrdCtrl")',
                    data: dataObj,
                    contentType: 'application/json',
                    dataType: 'html',
                    type: 'GET',
                    cache: false,
                    success: function (data) {
                            $('#searchResults').html(data);
                    },
                    error: function (jqXHR, textStatus) {
                        alert('jqXHR.statusCode');
                    }
                });
            });
    });
    </script>
}

回答1:


just don't populate the values in dataObj in your javascript unless the form field values are set.

so updating the declaration of dataObj to something like:

var dataObj = {};
if ($('#yearID').val() !== '') {
    dataObj.OrdYear = $('#yearID').val();
}
if ($('#OrdNumb').val() !== '') {
    dataObj.OrderNumber = $('#OrdNumb').val();
}
... etc ...

Should remove the empty query parameters on the GET request.



来源:https://stackoverflow.com/questions/42794320/how-to-ignore-empty-values-when-passing-a-viewmodel-object-via-ajax-to-an-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!