0

所以我有一个像这样的视图模型

public class TestViewModel
{
    public DateTime? StartDate { get; set; }

    public DateTime StartDate2 { get; set; }
}

使用该视图模型,我希望如果我通过 ajax 的 JSON 向这些属性发送“NULL”,那么这些属性的值是StartDate = nullStartDate2 = {01/01/0001 00.00.00}

这在我的本地机器上按预期工作,但在我的服务器上它返回错误Bad Request

我知道我的服务器返回Bad Request是因为模型绑定的事情

为什么我的服务器与本地机器的行为不同?我该如何解决这个问题?

编辑 :

顺便说一句,如果我将StartDateandStartDate2类型更改为string. 它没有错误,代码完美运行

这是我在控制器中的操作

public ActionResult TestAction(List<TestViewModel> p_viewModel)
{
   //The code actually does not reach here, because it fail on model binding ?

   // bla bla bla some logic here
}

这是我的 javascript

function getData()
{
    let datas = [];

    $("#tableListMeeting tbody tr").each(function (i, row) {
        let rowItem = $(row);
        let startDate = rowItem.find(`input[name$=".StartDate"]`).val();

        //change date format
        startDate = (startDate == "") ? null : moment(startDate, "DD-MM-YYYY").format("YYYY/MM/DD");
    
        let item = {
            StartDate: startDate
        };

        datas.push(item);
    });
    return datas;
}


function onButtonClick(){
    let data = getData();

    let URL_TO_ACTION  = "......"; //url to my action
    
    $.ajax({
        url: URL_TO_ACTION,
        type: 'post',
        datatype: 'json',
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            console.log("ajax local event 'sucess'");
            console.log(response);
        },
        error: function (jqXHR, ajaxOptions, thrownError) {
            if (jqXHR.status == 400) {
                let a = jqXHR.responseText;

                //logic to print error message
            } else {
                alert("Something went wrong, please try again");
            }
        },
        beforeSend: function () {
            console.log("ajax local event 'beforeSend'");
        }
}
4

1 回答 1

0

您应该显示更多代码以找出问题所在。

这是您的 View 模型的工作示例的小提琴。

https://dotnetfiddle.net/Eu7ayF

控制器:

[HttpPost]
public JsonResult GetAnswer(TestViewModel data)
{               
   Console.WriteLine(data.StartDate);
   return Json(data);
}

使用 ajax 帖子查看。

@model HelloWorldMvcApp.TestViewModel
@{
    Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap 101 Template</title>

        <!-- CSS Includes -->
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        
        <style type="text/css">

            .field-validation-error {
                color: #ff0000;
            }

        </style>
    </head>
    
    <body>
        <div class="container">
            <div class="col-md-6 col-md-offset-3">
                <h1>Hello Stranger</h1>
    
                @using (Html.BeginForm())
                {
                    <div class="form-group">
                        @Html.LabelFor(m => m.StartDate)
                        @Html.TextBoxFor(model => model.StartDate, new {@class="form-control"}) 
                        @Html.ValidationMessageFor(model => model.StartDate)
                    </div>                  
                    <div class="form-group">
                        @Html.LabelFor(m => m.StartDate2)
                        @Html.TextBoxFor(model => model.StartDate2, new {@class="form-control"}) 
                        @Html.ValidationMessageFor(model => model.StartDate2)
                    </div>
                
                    <button type="button" class="btn btn-success submit">Post Ajax</button>
                }
    
                <br/><br/>
                <div class="alert alert-warning fade">
                    <img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
                    <strong><span class="alert-content"></span></strong>
                </div>
            </div>
        </div>

        <!-- JS includes -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    
        <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
        <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
        
        <script type="text/javascript">
        
            $(function(){       
                $('.submit').click(function(){
                    if($('form').valid()) {
                    
                        $.ajax({
                            url: '@Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
                            data: {startDate2: $('#startDate2').val(), startDate: $('#startDate').val()},
                                type: 'POST',
                                dataType: 'json',
                                contentType: "application/json; charset=utf-8",
                                success: function(resp) {
                                    alert(resp.StartDate);
                                    alert(resp.StartDate2);
                        }});
                    }
                });
            
            });

        </script>
    </body>
</html>
于 2021-06-22T14:10:48.013 回答