AJAX 发布到 ASP.NET MVC 控制器操作方法 - 空参数

我想用 AJAX 将带有一些数据的字符串数组发布到我的控制器。它只是纯文本,我的控制器总是收到一个空参数。我知道我不应该字符串化,因为我不使用模型或视图模型。


我搜索了其他问题,但大多数是指表单并使用视图模型属性。


这是我的代码:


控制器


[HttpPost]

public ActionResult FirstAjax(string[] listValues)

{

    //TODO

    return Json("Reached the controller", JsonRequestBehavior.AllowGet);

}

我添加了 JSON 返回来检查我是否真的点击了控制器,并在我的视图中收到了消息。


AJAX POST


var listValues = [];

listElements.each(function (index, element) {

    listValues.push(element.innerText);

});


var serviceURL = '/Products/FirstAjax';


$.ajax({

    type: "POST",

    url: serviceURL,

    data: listValues,

    success: successFunc,

    error: errorFunc

});


function successFunc(data, status) {

    alert(data);

}


function errorFunc() {

    alert('error');

}

由于我的列表可以通过拖放进行排序,因此在单击按钮时按顺序listValues填充<li>项目的文本值。


看法


<div class="demo">


  <ul id="sortable">

    <li class="ui-state-default">Cat</li>

    <li class="ui-state-default">Dog</li>

    <li class="ui-state-default">Tiger</li>

  </ul>

  <button type="button" onclick="display_array();">Ajax Post!</button>


</div><!-- End demo -->


largeQ
浏览 175回答 3
3回答

慕的地8271018

编写您的 Ajax POST 方法如下:$(document).ready(function(){&nbsp; &nbsp; var listValues = [];&nbsp; &nbsp; listElements.each(function (index, element) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listValues.push(element.innerText);&nbsp; &nbsp; });&nbsp; &nbsp; var serviceURL = '/Products/FirstAjax';&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp;type: "POST",&nbsp; &nbsp; &nbsp; &nbsp;url: serviceURL,&nbsp; &nbsp; &nbsp; &nbsp;data: {listValues: listValues},&nbsp; &nbsp; &nbsp; &nbsp;contentType: 'application/json'&nbsp; &nbsp; &nbsp; &nbsp;success: successFunc,&nbsp; &nbsp; &nbsp; &nbsp;error: errorFunc&nbsp; &nbsp; });&nbsp; &nbsp; function successFunc(data, status) {&nbsp; &nbsp; &nbsp; &nbsp;alert(data);&nbsp; &nbsp; }&nbsp; &nbsp; function errorFunc() {&nbsp; &nbsp; &nbsp; &nbsp;alert('error');&nbsp; &nbsp; }});希望这能解决您的问题。

明月笑刀无情

您需要contentTypeasapplication/json和 useJSON.stringify将 JavaScript 对象转换为 JSON 字符串。$.ajax({&nbsp; &nbsp; type: "POST",&nbsp; &nbsp; contentType: "application/json; charset=utf-8",&nbsp; &nbsp; url: serviceURL,&nbsp; &nbsp; data: JSON.stringify({ listValues: listValues}),&nbsp; &nbsp; success: successFunc,&nbsp; &nbsp; error: errorFunc});

慕运维8079593

将您的 ajax 选项更改为:$.ajax({&nbsp; &nbsp; ...&nbsp; &nbsp; data: {listValues: listValues},&nbsp; &nbsp; ...});原因是:服务器期望发布的对象/查询字符串与参数命名相同。将data被转换为listValues=...&otherParams=...在查询字符串。如果您在未指定参数名称的情况下发布数组,则 JQuery 无法正确映射它们
打开App,查看更多内容
随时随地看视频慕课网APP