简体   繁体   English

如何使用 Json 数据作为参数进行 Jquery Ajax 调用?

[英]How to make an Jquery Ajax call with Json data as parameter?

I'm making an ajax call to Action in ASP.NET MVC framework.我正在 ASP.NET MVC 框架中发出 ajax 行动号召。 In Action string jsonModel is always getting as null.在操作中,字符串 jsonModel 始终为 null。 What I missing here?我在这里错过了什么? Can you please help?你能帮忙吗?

FYI -- I'm trying to keep the signature of the Action same as I'm using an existing action.仅供参考——我试图保持动作的签名与我使用现有动作的签名相同。 It would be great if we could check the way we are sending Json data to Action and why following action is failing to get the Json string.如果我们可以检查我们将 Json 数据发送到 Action 的方式以及为什么后续操作无法获取 Json 字符串,那就太好了。

Ajax Call: Ajax 致电:

function send(SubmissionID, EntityOrganizationID) {
    var user = $('#commentrecipients').val();
    var comment = $('#Comment').val();  

    var scObj = {};
    scObj["EntityOrganizationID"] = EntityOrganizationID;
    scObj["SubmissionID"] = SubmissionID;
    scObj["Comment"] = comment;
    scObj["RecipientModels"] = user;

    
    var jsonModel = JSON.stringify(scObj);
    alert(jsonModel);

    $.ajax({
        url: "/Submission/SubmissionHeaderCommentAction",
        dataType: "JSON", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
        data: jsonModel,
        async:false,
        success: function (result) {
            // notify the data source that the request succeeded
            options.success(result);
        },
        error: function (result) {
            // notify the data source that the request failed
            options.error(result);
        }
    });

Action:行动:

[AuditItem("SubmissionHeaderCommentAction")]
        public ActionResult SubmissionHeaderCommentAction(string jsonModel) // jsonModel comes as null
        {
            //convert json to our poco model
            dynamic data = JObject.Parse(jsonModel);
.........

  return AdComplianceStatusResult(HttpStatusCode.OK, "Comment submitted successfully");
        }

try it:试试看:

 var jsonModel = JSON.stringify(scObj);

  var newObj = {data:jsonModel };//<===========  
  var newJsonModel  = JSON.stringify(newObj);//<===========

$.ajax({
            url: "/Submission/SubmissionHeaderCommentAction",
            dataType: "application/json",  //<=========
            data: newJsonModel ,//<===========
            async:false,
            success: function (result) {
                // notify the data source that the request succeeded
                options.success(result);
            },
            error: function (result) {
                // notify the data source that the request failed
                options.error(result);
            }
        });

Action:行动:

[AuditItem("SubmissionHeaderCommentAction")]
        public ActionResult SubmissionHeaderCommentAction([FromBody]string data ) //<==============
        {
            //convert json to our yourPocoModel
           dynamic obj = JObject.Parse(data); 

  return AdComplianceStatusResult(HttpStatusCode.OK, "Comment submitted successfully");
        }

*** Uodated *** 无日期

I think you should change your concept to make things easier:我认为你应该改变你的概念以使事情变得更容易:

function send(SubmissionID, EntityOrganizationID) {
    var user = $('#commentrecipients').val();
    var comment = $('#Comment').val();  

    var scObj = new Object();
    scObj.entityOrganizationID = EntityOrganizationID;
    scObj.submissionID = SubmissionID;
    scObj.comment = comment;
    scObj.recipientModels = user;

    
    var jsonModel = JSON.stringify(scObj);
    alert(jsonModel);

    $.ajax({
        url: "/Submission/SubmissionHeaderCommentAction",
        dataType: "JSON", // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
        data: jsonModel,
        async:false,
        success: function (result) {
            // notify the data source that the request succeeded
            options.success(result);
        },
        error: function (result) {
            // notify the data source that the request failed
            options.error(result);
        }
    });

And simply return json:并简单地返回 json:

public JsonResult SubmissionHeaderCommentAction(int entityOrganizationID, int submissionID, string comment, string  recipientModels)
    {
                //so something with data
    
      return Json("Comment submitted successfully", JsonRequestBehavior.AllowGet);
    }

fix your ajax修复你的 ajax

function send(SubmissionID, EntityOrganizationID) {
    var user = $('#commentrecipients').val();
    var comment = $('#Comment').val();  

    var jsonModel= 
    {
      entityOrganizationID: EntityOrganizationID,
    submissionID : SubmissionID,
    comment : comment,
   recipientModels = user
};
    $.ajax({
       url: "/Submission/SubmissionHeaderCommentAction",
         data: {jsonModel},
         success: function (result) {
            // notify the data source that the request succeeded
            options.success(result);
        },
        error: function (result) {
            // notify the data source that the request failed
            options.error(result);
        }
    });

IMHO much better way to use viewModel恕我直言,使用 viewModel 的更好方法

public CommentViewModel
{
public int EntityOrganizationID {get; set;}, 
public int SubmissionID {get; set;}, 
public string Comment {get; set;}, 
public string  RecipientModels {get; set;}
}

with this action用这个动作

public IActionResult SubmissionHeaderCommentAction(CommentViewModel viewModel )
    {

     //do something with data
    
      return Ok("Comment submitted successfully");
    }

UPDATE更新

If you need to use existing action you can use this code ( it was tested in Visual Studio)如果您需要使用现有操作,您可以使用此代码(已在 Visual Studio 中测试)

public IActionResult SubmissionHeaderCommentAction(string jsonModel)
    {

CommentViewModel result= JsonConvert.DeserializeObject<CommentViewModel>(jsonModel);
    
     ....your code
    }

and use this ajax并使用这个 ajax


function send(SubmissionID, EntityOrganizationID) {
    var user = $('#commentrecipients').val();
    var comment = $('#Comment').val();  

    var jsonObj= 
    {
      entityOrganizationID: EntityOrganizationID,
    submissionID : SubmissionID,
    comment : comment,
   recipientModels = user
  };
var jsonModel= = JSON.stringify(jsonObj);

    $.ajax({
       url: "/Submission/SubmissionHeaderCommentAction",
         data: { JsonModel:jsonModel },
         success: function (result) {
            // notify the data source that the request succeeded
            options.success(result);
        },
        error: function (result) {
            // notify the data source that the request failed
            options.error(result);
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM