我有一个名为的模型类ReferralModel
,该类具有包含其他对象的属性:
public class ReferralModel
{
public Referral Referral { get; set; }
public Address Address { get; set; }
public Patient Patient { get; set; }
}
这是Address
该类的示例:
public class Address
{
public int Id { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public bool IsPrimary { get; set; }
}
我想在客户端构造对象以通过Ajax发送,但是在尝试以这种方式构造对象时遇到语法错误:
var request = $.ajax({
type: "POST",
url: "@Url.Action("AjaxCreateReferral", "Referral")",
data: JSON.stringify({
referralModel: {
ReferralModel.Address.Address1: $("#txtAddress1").val(),
ReferralModel.Address.Address2: $("#txtAddress2").val()
}
}),
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (response)
{
var dataObject = jQuery.parseJSON(response);
$("#hidPatientId").text(dataObject.patientId);
}
});
Visual Studio不喜欢这ReferralModel.Address.Address1
行。有没有办法正确地构造它?
谢谢!
出色地
referralModel: {
ReferralModel.Address.Address1: $("#txtAddress1").val(),
ReferralModel.Address.Address2: $("#txtAddress2").val()
}
似乎不太接近匹配:
public class ReferralModel
{
public Referral Referral { get; set; }
public Address Address { get; set; }
public Patient Patient { get; set; }
}
您要匹配属性名称而不是类型,因此它应该看起来像:
// Start of the object in the signature
// in the example below will be ReferralModel model
{
// name of a property in the signature model
// model.Address
Address:
{
// name of a property in the class of the previous property
// model.Address.Address1 (etc)
Address1: $("#txtAddress1").val(),
Address2: $("#txtAddress2").val()
}
}
假设您有一个签名类似的方法:
public ActionResult Index(ReferralModel model)
{
//...
}
另外,这实际上不是处理返回的JSON的首选方法。
dataType: "text",
success: function (response)
{
var dataObject = jQuery.parseJSON(response);
$("#hidPatientId").text(dataObject.patientId);
根据jQuery Docs:
dataType(默认值:Intelligent Guess(xml,json,脚本或html))
..如果未指定,则jQuery将尝试根据响应的MIME类型来推断它(XML MIME类型将产生XML,在1.4中,JSON将产生JavaScript对象。
因此可以轻松地将其简化为:
success: function (dataObject)
{
$("#hidPatientId").text(dataObject.patientId);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句