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

How to pass strongly typed complex object to ajax method in mvc3

我有一个名为 ReferralModel 的模型 class,它具有由其他对象组成的属性:

public class ReferralModel
{
    public Referral Referral { get; set; }
    public Address Address { get; set; }
    public Patient Patient { get; set; }
}

这是 Address class 的示例:

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

dataType (default: Intelligent Guess (xml, json, script, or html))

..if none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object..

所以它可以很容易地简化为:

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