【问题标题】:jquery.POST to MVC controller to return JSONjquery.POST 到 MVC 控制器以返回 JSON
【发布时间】:2012-11-01 22:57:13
【问题描述】:

我创建了以下模型

public class myModel
{
    public int ID;
    public string Name;
    public int[] days;
}

然后我在控制器中创建了一个动作

[HttpPost]
public ActionResult myCtrlAction(myModel thisModel)
{
   if (ModelState.IsValid)
        {
            return Json(thisModel);
        }
        else
        {
            string errorMessage = "<div class=\"validation-summary-errors\">"
              + "The following errors occurred:<ul>";
            foreach (var key in ModelState.Keys)
            {
                var error = ModelState[key].Errors.FirstOrDefault();
                if (error != null)
                {
                    errorMessage += "<li class=\"field-validation-error\">"
                     + error.ErrorMessage + "</li>";
                }
            }
            errorMessage += "</ul>";
            return Json(new myModel { Name = errorMessage });  //just for now
        } 
   }

在我的 javascript 中,我使用 jQuery.post() 作为发送数据

$("#myBtn").click(function () {
var mydata = {
          ID: $("#inputID").val(),
          Name: $("#inputName").val(),
          Days: $("#selectDays").select2("val")
       }
    var url = 'myController/myCtrlAction';  //definitly it was writtern as @Url.Action
    $.post(url, mydata, function(data) { alert(data); //which shows [object object] 
                     }, 'json');
 });

现在应要求,当我在 Chrome 中调试时,我在标题中看到

表单数据 编号:5 姓名:某名 天数[]:6 天数[]: 5

作为响应,我得到了我的模型的 json 格式

{ID: "0", Name: "null", Days: "null"} 这意味着我的模型状态有效但为什么它没有值?

任何人都有任何想法。我做错了什么还是错过了什么?

【问题讨论】:

    标签: c# asp.net-mvc json razor


    【解决方案1】:

    我认为您的模型数据未设置,因此您在 Chrome 上得到空值。

    如果您的 javascript 没有错字(并且您只是在创建问题时打错字,请在您的方法 myCtrlAction 中尝试此操作;

    首先尝试为 myModel 中的字段创建 getter 和 setter。然后;

    替换;

     errorMessage += "</ul>";
    
     return Json(new myModel { Name = errorMessage });  //just for now
    

    有了这个;

     myModel myMODTest= new myModel();
     myMODTest.setID(1111);
     myMODTest.setName("testName");
     myMODTest.setDays({1,2,3});
     return Json(myMODTest);  //just for now
    

    看看你的浏览器有没有以下内容;

    {ID: "1111", Name: "testName", Days: "{1,2,3}"}

    【讨论】:

    • 让我看看,是的,我错过了设置 Awwww 来吧。怎么可能。谢谢mwangi。
    • 谢谢。对我自己大声笑。这不应该是问题,但你得到了投票。干杯!
    • 嗨,你能告诉我为什么我的模型中没有收到数组,即使我为数组 int[] 天放置了 getter setter。在 Chrome 开发人员工具中,数组显示为 Days[]: 6 和 Days[]: 5。作为响应,我的模型中的 Days 为 NULL。我在模型中将其更改为 List Days 它仍然在响应中返回 null。
    • 您能否分享一个屏幕截图,说明当您使用 int[] 几天后它在 Chrome 开发者工具中的显示方式?
    • 我明白了,我必须写,传统的:在 jquery ajax 中为真。谢谢。干杯
    【解决方案2】:

    我这样做:

    • 1:JavaScript:点击按钮时:序列化表单数据并将其发送到控制器:

      function ajaxSubmitEditSupplierQuote() {
          var formData = $("#SupplierQuoteEditForm").serializeArray();
          $.ajax({
              type: "POST",
              url: '@Url.Action("Edit", "SupplierQuote")',
              data: formData,
              dataType: "json",
              cache: false,
              success: function (data1) {
                  // Here I create then a new Url-string.   
                  // Simple access your Json Data, as you have named it in the return of the Controller-Action.
                  var strUrl = "/Equipment/" + data1.target.toString();                   
                  // ...
                  // 
                  // ...
              }
          });
      }        
      
    • 2:带有自定义 Json 返回的 Controller-Action

      [HttpPost]
      public ActionResult Edit(SupplierQuoteDto supplierQuoteDto)
      {
      
          // ........... code
      
          if (_userContext.EquipmentAction.ClickedAction == ActionType.Create)
              return Json(new { target = "Create" });
          else if (_userContext.EquipmentAction.ClickedAction == ActionType.Edit)
              return Json(new { target = "Edit" });
          else
              return new EmptyResult();
      }
      
    • 3:或者,如果您还想在 JavaScript 中捕获 EmptyResult(),只需在

      中进行检查
      success: function (data1) { 
          if (data1.toString() == "") {
              // .... alert
          }
          else {
              /// .... go on with coding
          }
      }
      

    【讨论】:

      【解决方案3】:

      检查您发布帖子的 JavaScript 代码。你有一个错字:'。'而不是',':

      $.post(url, mydata, function(data) { alert(data); }, 'json');
      

      【讨论】:

      • 谢谢。错字已修复,但我担心的是为什么我在开发人员工具 (Chrome) 中看不到我在重新调整 json 时发送到 myController 的 CtrlAction 的值。
      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多