我使用.net核心。上这个课:
public class SentEmailItem
{
public SentEmailItem()
{
Attachments = new List<AttachmentItem>();
}
public long PKID { get; set; }
public string EmailTo { get; set; }
public string EmailFrom { get; set; }
public string Cc { get; set; }
public string Bcc { get; set; }
public string Body { get; set; }
public string Subject { get; set; }
public List<string> EmailToList => EmailTo.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> CcList => (Cc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<string> BccList => (Bcc ?? string.Empty).Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
public List<AttachmentItem> Attachments { get; set; }
}
控制器中的此方法:
[HttpPost]
public JsonResult SendEmail(SentEmailItem item)
{
EmailHelper.SendEmailAsync(item);
return SuccessJsonResult();
}
但是,当通过以下代码从ajax调用此方法时:
$.ajax({
type: "POST",
url: self.sendEmailUrl,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ item: emaiItem })
}).done(function (json) {
App.unblockUI();
if (json.HasErrors) {
var errorsHtml = $.map(json.Errors, function (x) { return "" + x.ErrorMessage + "<br/>"; }).join("");
UIToastr.ShowMessage('error', 'Error', errorsHtml);
return;
}
self.sendEmailCompleted(json);
});
我无法在控制器方法中获取数据。所有数据均为空值。但是在emaiItem中放置在js中的值看起来像:
Bcc : "[email protected]"
Body : "test body"
Cc : "[email protected]"
EmailFrom : "[email protected]"
EmailTo : "[email protected]"
Subject : "Test subject"
最佳答案
看来emaiItem
已经是这样的对象-
var emaiItem = {Bcc : "[email protected]",
Body : "test body",
Cc : "[email protected]",
EmailFrom : "[email protected]",
EmailTo : "[email protected]",
Subject : "Test subject"};
如果是这样,可以只使用
JSON.stringify(emaiItem)
。否则,您可以对上面的emaiItem
进行硬编码,并查看在服务器端填充的那些值。$.ajax({
...
data: JSON.stringify(emaiItem)
}).done(function (json) {
...
});
解
替换为
JSON.stringify(emaiItem)
,然后使用[FromBody]
属性强制模型绑定程序绑定来自请求主体的数据。[HttpPost]
public JsonResult SendEmail([FromBody]SentEmailItem item)
{
}