jQuery 如何在没有表单的情况下将字符串数组发布到 ASP.NET MVC 控制器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/309115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I post an array of string to ASP.NET MVC Controller without a form?
提问by rodbv
I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function.
我正在创建一个小应用程序来自学 ASP.NET MVC 和 JQuery,其中一个页面是一个项目列表,其中可以选择一些项目。然后我想按下一个按钮并使用 JQuery 的 Post 函数向我的控制器发送一个列表(或等效的东西),其中包含所选项目的 id。
I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though.
我设法获得了一个包含所选元素的 id 的数组,现在我想发布它。我可以这样做的一种方法是在我的页面中有一个带有隐藏值的虚拟表单,然后使用所选项目设置隐藏值,然后发布该表单;不过,这看起来很粗糙。
Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far:
有没有更简洁的方法来实现这一点,通过将数组直接发送到控制器?我尝试了一些不同的东西,但看起来控制器无法映射它接收的数据。这是到目前为止的代码:
function generateList(selectedValues) {
var s = {
values: selectedValues //selectedValues is an array of string
};
$.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
}
And then my Controller looks like this
然后我的控制器看起来像这样
public ActionResult GenerateList(List<string> values)
{
//do something
}
All I managed to get is a "null" in the controller parameter...
我设法得到的只是控制器参数中的“空”...
Any tips?
有小费吗?
回答by MrDustpan
I modified my response to include the code for a test app I did.
我修改了我的回复以包含我所做的测试应用程序的代码。
Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).
更新:我已经更新了 jQuery 以将“传统”设置设置为 true,这样这将再次起作用(根据 @DustinDavis 的回答)。
First the javascript:
首先是javascript:
function test()
{
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/Home/SaveList",
data: postData,
success: function(data){
alert(data.Result);
},
dataType: "json",
traditional: true
});
}
And here's the code in my controller class:
这是我的控制器类中的代码:
public JsonResult SaveList(List<String> values)
{
return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!
当我调用该 javascript 函数时,我收到一条警告,提示“列表中的第一项:'item1'”。希望这可以帮助!
回答by Dustin Davis
FYI: JQuery changed the way they serialize post data.
仅供参考:JQuery 改变了他们序列化发布数据的方式。
http://forum.jquery.com/topic/nested-param-serialization
http://forum.jquery.com/topic/nested-param-serialization
You have to set the 'Traditional' setting to true, other wise
您必须将“传统”设置设置为真,否则
{ Values : ["1", "2", "3"] }
will come out as
会出来
Values[]=1&Values[]=2&Values[]=3
instead of
代替
Values=1&Values=2&Values=3
回答by Evgenii
Thanks everyone for the answers. Another quick solution will be to use jQuery.parammethod with traditionalparameter set to trueto convert JSON object to string:
谢谢大家的回答。另一个快速解决方案是使用jQuery.param方法并将传统参数设置为true将 JSON 对象转换为字符串:
$.post("/your/url", $.param(yourJsonObject,true));
回答by Craig Stuntz
Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.
不要将数据作为数组发布。 要绑定到列表,键/值对应该为每个键提交相同的值。
You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.
您不应该需要一个表格来执行此操作。您只需要一个键/值对列表,您可以将其包含在对 $.post 的调用中。
回答by Matas Vaitkevicius
In .NET4.5
, MVC 5
在.NET4.5
,MVC 5
Javascript:
Javascript:
object in JS:
JS中的对象:
mechanism that does post.
发布的机制。
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
C#
Objects:
对象:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
控制器:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
收到的对象:
Hope this saves you some time.
希望这可以为您节省一些时间。
回答by d.popov
Another implementation that is also working with list of objects, not just strings:
另一个也使用对象列表的实现,而不仅仅是字符串:
JS:
JS:
var postData = {};
postData[values] = selectedValues ;
$.ajax({
url: "/Home/SaveList",
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){
alert(data.Result);
}
});
Assuming that 'selectedValues' is Array of Objects.
假设“selectedValues”是对象数组。
In the controller the parameter is a list of corresponding ViewModels.
在控制器中,参数是对应的 ViewModel 的列表。
public JsonResult SaveList(List<ViewModel> values)
{
return Json(new {
Result = String.Format("Fist item in list: '{0}'", values[0].Name)
});
}
回答by Mohsen Afshin
As I discussed here,
正如我在这里讨论的那样,
if you want to pass custom JSON object to MVC action then you can use this solution, it works like a charm.
如果您想将自定义 JSON 对象传递给 MVC 操作,那么您可以使用此解决方案,它就像一个魅力。
public string GetData() {
// InputStream contains the JSON object you've sent
String jsonString = new StreamReader(this.Request.InputStream).ReadToEnd();
// Deserialize it to a dictionary
var dic =
Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < String,
dynamic >> (jsonString);
string result = "";
result += dic["firstname"] + dic["lastname"];
// You can even cast your object to their original type because of 'dynamic' keyword
result += ", Age: " + (int) dic["age"];
if ((bool) dic["married"])
result += ", Married";
return result;
}
The real benefit of this solution is that you don't require to define a new class for each combination of arguments and beside that, you can cast your objects to their original types easily.
这个解决方案的真正好处是你不需要为每个参数组合定义一个新类,除此之外,你可以轻松地将对象转换为它们的原始类型。
You can use a helper method like this to facilitate your job:
您可以使用这样的辅助方法来促进您的工作:
public static Dictionary < string, dynamic > GetDic(HttpRequestBase request) {
String jsonString = new StreamReader(request.InputStream).ReadToEnd();
return Newtonsoft.Json.JsonConvert.DeserializeObject < Dictionary < string, dynamic >> (jsonString);
}
回答by mr_squall
You can setup global parameter with
您可以设置全局参数
jQuery.ajaxSettings.traditional = true;
回答by DavidW
The answer helped me a lot in my situation so thanks for that. However for future reference people should bind to a model and then validate. This post from Phil Haack describes this for MVC 2. http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
在我的情况下,答案对我帮助很大,所以谢谢你。但是,为了将来参考,人们应该绑定到模型然后进行验证。Phil Haack 的这篇文章描述了 MVC 2。http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Hope this helps someone.
希望这可以帮助某人。