AJAX를 통해 배열을 mvc 동작으로 전달
AJAX를 통해 MVC 작업에 배열 (또는 IEnumerable)의 정수를 전달하려고하는데 약간의 도움이 필요합니다.
자바 스크립트는
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
컨트롤러 동작은
public ActionResult MyAction(IEnumerable<int> arrayOfValues )
현재 요청의 형식은 다음과 같습니다.
controller/MyAction?_=1301503418429&arrayOfValues[]=491&arrayOfValues[]=368&arrayOfValues[]=235&arrayOfValues[]=437
그래서 나는 거의 거기에 있습니다. 대괄호를 제거하면 올바른 응답을 얻습니다. 컨트롤러가 배열을 인식 할 수 있도록 배열을 get에 어떻게 전달해야합니까?
도와 주셔서 감사합니다
데이브
전화를 받기 전에 전통적인 속성을 true로 설정하십시오. 즉 :
jQuery.ajaxSettings.traditional = true
$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...
POST를 수행하려고 시도 할 때 과거에 문제가 발생했습니다 (정확히 수행중인 작업인지 확실하지 않지만 배열을 전달할 때 traditional을 전통으로 설정해야합니다) .
var arrayOfValues = new Array();
//Populate arrayOfValues
$.ajax({
type: "POST",
url: "<%= Url.Action("MyAction","Controller")%>",
traditional: true,
data: { 'arrayOfValues': arrayOfValues }
});
이미 늦었지만 여기에 이미 나와있는 답변에 대해 다른 답변이 있습니다.
대신의 경우 $.ajax
당신 속기 기능을 사용하고 싶습니다 $.get
나 $.post
당신이 배열이 방법을 전달할 수 :
속기 GET
var array = [1, 2, 3, 4, 5];
$.get('/controller/MyAction', $.param({ data: array }, true), function(data) {});
// Action Method
public void MyAction(List<int> data)
{
// do stuff here
}
속기 POST
var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});
// Action Method
[HttpPost]
public void MyAction(List<int> data)
{
// do stuff here
}
노트:
- 부울 매개 변수
$.param
는traditional
속성에 대한 것이며 , 반드시true
작동 해야합니다 .
'전통적인'옵션을 사용하는 정답입니다. 자세한 내용을 알고 싶은 사람에게 더 많은 배경 정보를 제공하고 있습니다.
jQuery 문서에서 :
jQuery 1.8부터 $ .param () 메소드는 더 이상 jQuery.ajaxSettings.traditional을 기본 설정으로 사용하지 않으며 기본값은 false입니다.
You can also read more here: http://michaelsync.net/2012/04/05/tips-asp-net-mvc-javascriptserializer-3-questions-and-3-answers and http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
HTH
You should be able to do this just fine:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Then your action method would be like so:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.
IF ALL ELSE FAILS...
None of the other answers here solved my problem. I was attempting to make a GET method call from JavaScript to an MVC Web API controller, and to send an array of integers as a parameter within that request. I tried all the solutions here, but still the parameter on my controller was coming up NULL (or Nothing for you VB users).
I eventually found my solution in a different SO post, and it was actually really simple: Just add the [FromUri]
annotation before the array parameter in the controller (I also had to make the call using the "traditional" AJAX setting to avoid bracket annotations). See below for the actual code I used in my application.
Controller Signature:
NOTE: The annotation in C# would be
[FromUri]
JavaScript:
$.get('/api/InventoryApi/GetBalanceField', $.param({productIds: [42], inventoryFormId: 5493, inventoryBalanceType: 'Beginning'},true)).done(function(data) {console.log(data);});
Actual URL String:
http://randomhostname/api/InventoryApi/GetBalanceField?productIds=42&inventoryFormId=5493&inventoryBalanceType=Beginning
If you are migrating to ASP.NET Core MVC from .Net Framework MVC like I was, things have changed slightly. The ajax call must be on the raw object using stringify so rather than passing data of { vals: arrayOfValues }
it should be JSON.stringify(arrayOfValues)
as follows:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify(arrayOfValues),
success: function(data) { /* Whatever */ }
});
The other change that has been made in ASP.NET Core is to prevent cross-site request forgery so for calls to an MVC action from an ajax method the [FromBody]
atribute must be applied to the action parameter as follows:
public ActionResult MyAction([FromBody] IEnumerable<int> arrayOfValues )
A bit late here, but I could use SNag's solution further into $.ajax(). Here is the code if it would help anyone:
var array = [1, 2, 3, 4, 5];
$.ajax({
type: "GET",
url: '/controller/MyAction',
data: $.param({ data: array}, true),
contentType: 'application/json; charset=utf-8',
success: function (data) {
},
error: function (x, y, z) {
}
});
// Action Method
public void MyAction(List<int> data)
{
// do stuff here
}
If you're using ASP.NET Core MVC and need to handle the square brackets (rather than use the jQuery "traditional" option), the only option I've found is to manually build the IEnumerable
in the contoller method.
string arrayKey = "p[]=";
var pArray = HttpContext.Request.QueryString.Value
.Split('&')
.Where(s => s.Contains(arrayKey))
.Select(s => s.Substring(arrayKey.Length));
You need to convert Array to string :
//arrayOfValues = [1, 2, 3];
$.get('/controller/MyAction', { arrayOfValues: "1, 2, 3" }, function (data) {...
this works even in form of int, long or string
public ActionResult MyAction(int[] arrayOfValues )
참고URL : https://stackoverflow.com/questions/5489461/pass-array-to-mvc-action-via-ajax
'Programming' 카테고리의 다른 글
'ViewController'클래스에 신속한 초기화 기능이 없습니다. (0) | 2020.07.13 |
---|---|
일정 시간이 지나면 웹 사이트 리디렉션 (0) | 2020.07.13 |
요소가 존재할 때까지 기능 대기 (0) | 2020.07.13 |
uwsgi 잘못된 요청 블록 크기 (0) | 2020.07.13 |
iPhone 시뮬레이터 용 스크린 샷 앱 (0) | 2020.07.13 |