如何将MVC模型传递给控制器​​动作

时间:2018-07-19 11:19:03

标签: javascript model-view-controller model controller

我尝试将MVC模型对象从JavaScript传递到Controller Action,但是经过一天多的尝试后,它要么是null要么是错误。

Controller自变量JC始终为null

我的JavaScript代码:

$(function() {
  $(".dialog-modal").dialog({
    height: 140,
    modal: true
  });
});

$(function() {
  $("#job-save").dialog({
    height: 240,
    modal: true
  });
});

$("#job-save").dialog({
  close: function(event, ui) {
    window.location.href = "/EquipmentAll";
  }
});

$(function() {
  $("#ContactKey").change(function() {
    var t = $(this).val();

    if (t !== "") {
      $.post("@Url.Action("GetContactDefaults")?val=" + t + "&JC=" + @Model,
        function(res) {
          if (res.Success === "true") {
            //enable the text boxes and set the value
            $("#ContactEmail").prop('disabled', false).val(res.Data.EmailAddress);
            $("#Height").prop('disabled', false).val(res.Data.Height);
          } else {
            alert("Error getting data!");
          }
        }
      )
    } else {
      //Let's clear the values and disable :)
      $("input.editableItems").val('').prop('disabled', true);
    }
  });
});

我的控制器操作代码为:

[HttpPost]
public ActionResult GetContactDefaults(string val, JobCreate JC)
{
    //Contact tContact = JC.ContactList.FirstOrDefault(c => c.ContactKey == val);
    if (val != "")
    {
        // Values are hard coded for demo. you may replae with values 
        // coming from your db/service based on the passed in value ( val.Value)
        return Json(new { Success = "true", Data = new { EmailAddress = "col@ss", TelAreaCode = 345, TelNo = 100, ACa = "444" } });
    }
    return Json(new { Success = "false" });
}

1 个答案:

答案 0 :(得分:0)

您应该序列化模型,并插入Html.Raw。我建议在POST正文中传递对象而不是GET参数:

  1. 在您看来,将对象放入请求正文:

    var callback = function(res) {
    
       if (res.Success === "true") {
    
        //enable the text boxes and set the value
    
        $("#ContactEmail").prop('disabled', false).val(res.Data.EmailAddress);
        $("#Height").prop('disabled', false).val(res.Data.Height);
    
       } else {
        alert("Error getting data!");
       }
     });
    
    
    $.post("@Url.Action("GetContactDefaults")?val=" + t, "@Html.Raw(Json.Encode(Model))", callback, 'json');
    
  2. 在控制器中添加参数属性:

    [HttpPost]
    public ActionResult GetContactDefaults([FromQuery]string val, [FromBody]JobCreate JC)
    
相关问题