通过Ajax将ViewModel(对象)传递给MVC控制器时,如何忽略空值 [英] How to ignore empty values when passing a ViewModel (object) via Ajax to an MVC controller

查看:90
本文介绍了通过Ajax将ViewModel(对象)传递给MVC控制器时,如何忽略空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的view中,我将对象(ViewModel)传递给控制器​​.如果用户在表格中输入所有值,则效果很好.通过LINQ查询生成的带有querystring的示例请求的URL如下:

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

但是,如果用户跳过在搜索表单中输入一个值,例如orderName,则用户将得到预期的错误:

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.

我认为发生上述错误是因为生成的请求的URL缺少orderName的参数值,如下所示:

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

问题:在下面的Ajax调用内的dataObj中,如果输入参数的值为空字符串,我们如何跳过输入参数-因此生成的查询字符串不包含这些参数. 注意:这是一个搜索表单,只允许用户根据他们在表单中输入的值进行搜索.

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; }
}

查看:

@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>
}

推荐答案

除非设置了表单字段值,否则请不要在JavaScript中填充dataObj中的值.

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

因此将dataObj的声明更新为以下内容:

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

应删除GET请求中的空查询参数.

Should remove the empty query parameters on the GET request.

这篇关于通过Ajax将ViewModel(对象)传递给MVC控制器时,如何忽略空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆