简体   繁体   English

通过Ajax将ViewModel(对象)传递给MVC控制器时,如何忽略空值

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

In the following view I'm passing an Object (ViewModel) to controller. 在下面的view我将一个对象(ViewModel)传递给控制器​​。 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: 通过LINQ查询生成的带有querystring的示例请求URL如下:

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: 但是,如果用户跳过在搜索表单中输入一个值(例如orderName则用户将得到预期的错误:

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: 我认为会发生上述错误,因为生成的Requested URL缺少orderName的参数值,如下所示:

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. 问题 :在下面的Ajax调用中的dataObj中,如果输入参数的值为空字符串,如何跳过输入参数-因此生成的查询字符串不包含那些参数。 NOTE : This is a search form and users are allowed to search based only on the values they enter inside form. 注意 :这是一个搜索表单,只允许用户根据他们在表单中输入的值进行搜索。

TestViewModel: 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>
}

just don't populate the values in dataObj in your javascript unless the form field values are set. 除非设置了表单字段值,否则不要在JavaScript中填充dataObj中的值。

so updating the declaration of dataObj to something like: 因此,将dataObj的声明更新为:

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. 应该删除GET请求上的空查询参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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