如何将强类型复杂对象传递给mvc3中的ajax方法

时间:2015-03-06 15:00:28

标签: jquery ajax asp.net-mvc-3

我有一个名为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行。有没有办法正确构建这个?

谢谢!

1 个答案:

答案 0 :(得分:2)

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文档:

  

dataType(默认值:Intelligent Guess(xml,json,script或html))

     

..如果没有指定,jQuery将尝试根据响应的MIME类型推断它(XML MIME类型将产生XML,在1.4 JSON中将产生一个JavaScript对象..

因此可以很容易地简化为:

success: function (dataObject)
{
  $("#hidPatientId").text(dataObject.patientId);