【问题标题】:AJAX POST rows of data in MVC always nullAJAX POST MVC 中的数据行始终为空
【发布时间】:2018-03-21 21:55:06
【问题描述】:

谁能帮我解决以下问题。我正在尝试将 JSON 数据发布到控制器,但控制器从不使用数据填充变量。

这是控制器,总是显示为空。

这是控制器。

public ActionResult SyncMail(List<MailSyncDTO> emailLst)
{
    return null;
}

视图如下所示;

foreach (var item in Model)
    <td><input name="emailLst.emailSource" id="emailSource" type="text" value="@item.emailSource" /></td>
    <td><input name="emailLst.emailDestination" id="emailDestination" type="text" value="@item.emailDestination" /></td>
    <td><input name="emailLst.SyncMail" id="SyncMail" type="checkbox" /></td>
    <td><input name="emailLst.ID" id="ID" type="text" value="@item.ID" hidden /></td>
</tr>
}

    function Update() {
        var emailLst = [];
        $('#tblEmails tr').each(function () {
            var obj = new Object();
            var emailSource = $(this).find("input").each(function () {
                if (this.id == 'emailSource' && this.value != '') {
                    obj.emailSource = this.value;
                }
                else if (this.id == 'emailDestination' && this.value != '') {
                    obj.emailDestination = this.value;
                }
                else if (this.id == 'SyncMail' && this.value != '') {
                    obj.SyncMail = this.value;
                }
                else if (this.id == 'ID' && this.value != '') {
                    obj.ID = this.value;
                }
            })
            emailLst.push(obj);
        });

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/MailSyncDBs/SyncMail',
            data: JSON.stringify({ emailLst: emailLst })
        });
    }

我可以在 Fiddler 中看到正在发送数据。

POST http://localhost:53545/MailSyncDBs/SyncMail HTTP/1.1
Content-Type: application/json; charset=utf-8
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
Referer: http://localhost:53545/MailSyncDBs/Index
Accept-Language: en-GB
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Length: 336
Host: localhost:53545
Connection: Keep-Alive
Pragma: no-cache
{"emailLst":[{},{"emailSource":"source@mail.co.uk","emailDestination":"destination@mail.co.uk","SyncMail":"on","ID":"1"},{"emailSource":"source1@mail.co.uk","emailDestination":"destination1@mail.co.uk","SyncMail":"on","ID":"2"},{"emailSource":"source2@mail.co.uk","emailDestination":"destination2@mail.co.uk","SyncMail":"on","ID":"3"}]}

这是被引用的 DTO;

public class MailSyncDTO
{
    public string ID { get; set; }
    public string emailSource { get; set; }
    public string emailDestination { get; set; }
    public string SyncMail { get; set; }
}

【问题讨论】:

标签: json ajax asp.net-mvc null


【解决方案1】:

您的控制器想要接收List&lt;string&gt;,但您没有发送给他。在您制作控制器的方式中,您发送的 Json 应该如下所示:

["source@co.uk","source@co.uk","source@co.uk"]

您可以在您的 C# 项目中创建一个 DTO,它将完全反映您的 Json,并将自动映射到您的控制器中。

我已经用这个 javascript 方法对其进行了测试:

function testIt() {
    var emailLst = [];

    // Replace bellow part with yours
    var obj = new Object();
    obj.EmailDestination = "dest@co.uk";
    obj.Source = "source@Context.uk";
    obj.SyncMail = "on";
    obj.Id = "1";
    emailLst.push(obj);
    // Replace above part with yours


    // Adding this before sending will make sure that you are not sending any empty objects.
    emailLst.forEach(function(item, i) {         
        if ($.isEmptyObject(item)) {
            emailLst.splice(i, 1);
        }
    });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/MailSyncDBs/SyncMail',
        data: JSON.stringify(emailLst)  // And not JSON.stringify({emailLst : emailLst })
    });
}

尝试添加这样的类:

public class SyncMailDto
{
    public string EmailSource {get; set;}
    public string EmailDestination {get; set;}
    public string SyncMail {get; set;}
    public string Id {get; set;}    
}

并将控制器方法的签名更改为:

[HttpPost]
public JsonResult SyncMail(List<SyncMailDto> emailLst){

    foreach(var mail in emailLst){
         // Do something with your mail
    }

    return Json("It Works !");
}

如果您想完全使用您编写的 javascript,则必须添加另一个 DTO 类来包装列表。因为这就是你对 JSON.stringify({EmailLst : EmailLst}) 所做的。

public class MailListWrapperDto{
    public List<SyncMailDto> EmailLst {get;set;}
}

还有你的 POST 方法的签名:

public JsonResult SyncMail(MailListWrapperDto emailLst)

【讨论】:

  • 谢谢 Antoine,我明天早上试试。我是 Json 和 MVC 的新手,但我认为 json.stringify 在发送数据之前会将其转换为字符串。这不是错误的吗?
  • 也没有那么错误,但是你要转换的数据是对象列表,而不是字符串列表。确切地说,如果我是正确的,您不需要对 json 进行字符串化。
  • 我仍然无法让它工作。我开始了一个新项目,因为我把另一个项目弄得一团糟。我添加了一个带有字符串属性的 DTO。变量仍然为空。我已经用更新的 DTO 更新了原始问题并删除了图像。
  • @NathanLinus 我已经用 javascript 代码编辑了我的答案,并在 Visual Studio 2017 中对其进行了测试,它工作正常。真正的问题是您发送 Json 的方式。
  • 如果对您有帮助,请考虑将此标记为答案
猜你喜欢
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多