如何使用 jsonresult asp.net mvc3 返回多个变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10604014/
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 to return multiple variables with jsonresult asp.net mvc3
提问by Irakli Lekishvili
How to return multiple variables on JsonResult method
如何在 JsonResult 方法上返回多个变量
for example i want to return this two variables:
例如我想返回这两个变量:
string result = "Successed";
string ID = "32"
I know how to return only one string:
我知道如何只返回一个字符串:
return Json("Inserted");
回答by Shyju
public ActionResult YourAction()
{
var result=new { Result="Successed", ID="32"};
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT: As per the comment"How to get this data in client"
编辑:根据评论“如何在客户端获取此数据”
You can use getJSONfrom view to get this data like this
您可以使用getJSONfrom view 来获取这样的数据
$(function(){
$.getJSON('YourController/YourAction', function(data) {
alert(data.Result);
alert(data.ID);
});
});
Make sure you have jQuery loaded in your view for this code to work.
确保您在视图中加载了 jQuery 以使此代码正常工作。
回答by m0g3
On your controller use something like this:
在你的控制器上使用这样的东西:
var result = new { data= stuff, data2 = otherstuff };
return Json(result, JsonRequestBehavior.AllowGet);
If you are using .ajax() on your JavaScript you can use your data acessing like this:
如果你在你的 JavaScript 上使用 .ajax() 你可以像这样使用你的数据访问:
$.ajax(
{
url: '/Controller/Method/',
type: 'POST',
data: 'data=' + data,
success: function (result) {
$('#id').html("");
$(result.data).appendTo('#id');
$('#id2').html("");
$(result.data2).appendTo('#id2');
$('#id').show();
$('#id2').show();
}
});
回答by user2449131
1. Return as collection inside anonymous typeThis is the java script/ajax call and the complete html.
1.作为匿名类型内部的集合返回这是java脚本/ajax调用和完整的html。
< script type = "text/javascript" >
$(document).ready(function() {
$("#ddlProduct").hide();
$("#ddlRegion").change(function() {
$("#ddlProduct").show();
$("#ddlProduct").empty();
$.ajax({
type: "Post",
url: "@Url.Action("
GetProducts ")",
dataType: "Json",
data: {
id: $("#ddlRegion").val()
},
success: function(jsonData) {
console.log($(jsonData).length);
if ($(jsonData.ProductList).length == 0) {
$("#divProduct").hide();
} else {
$("#divProduct").show();
}
$.each(jsonData.ProductList, function(i, Product) {
$("#ddlProduct").append('<option value=" ' + Product.Value + ' ">' + Product.Text + '</option>');
});
if ($(jsonData.FlavourList).length == 0) {
$("#divFlavour").hide();
} else {
$("#divFlavour").show();
$.each(jsonData.FlavourList, function(i, flavour) {
$("#ddlFlavour").append('<option value=" ' + flavour.Value + ' ">' + flavour.Text + '</option>');
});
}
},
error: function(ex) {
alert("Failed to return Products <br/>");
}
});
return false;
})
}); //Document Ready Ends
< /script>
@{ ViewBag.Title = "Products Drop Down Demo"; }
<h2>Products Drop Down Demo</h2>
@using (Html.BeginForm()) {
<div>@Html.Label("Select Region:")</div>
<div class="editor-field">
@if (ViewData.ContainsKey("Region")) { @Html.DropDownList("ddlRegion", ViewData["Region"] as List
<SelectListItem>) }
</div>
<div id="divProduct" hidden="hidden">
<br />
<div>
Select a Product:
</div>
<div>
@Html.DropDownList("ddlProduct", new SelectList(string.Empty, "Value", "Text"), "Please select a Product", new { style = "width:250px", @class = "dropdown1" })
</div>
</div>
<div id="divFlavour" hidden="hidden">
<div>
<br />Select a Flavour:
</div>
<div>
@Html.DropDownList("ddlFlavour", new SelectList(string.Empty, "Value", "Text"), "Please select a Flavour", new { style = "width:250px", @class = "dropdown1" })
</div>
</div>
}
This is the controller action that returns the dataI tested and it is working.
这是返回我测试过的数据的控制器操作,它正在工作。
public ActionResult LoadRegion()
{
List<SelectListItem> Regions = new List<SelectListItem>();
Regions.Add(new SelectListItem { Text = "Select A Region", Value = "0" });
Regions.Add(new SelectListItem { Text = "Asea", Value = "1" });
Regions.Add(new SelectListItem { Text = "Australia", Value = "4" });
Regions.Add(new SelectListItem { Text = "America", Value = "5" });
Regions.Add(new SelectListItem { Text = "Europe", Value = "6" });
ViewData["Region"] = Regions;
return View();
}
public JsonResult GetProducts(string id) { List products = new List(); List flavours = new List();
public JsonResult GetProducts(string id) { List products = new List(); 列表口味 = new List();
products.Add(new SelectListItem { Text = "Select Product", Value = "0" });
products.Add(new SelectListItem { Text = "Cheese", Value = "1" });
products.Add(new SelectListItem { Text = "Sause", Value = "2" });
products.Add(new SelectListItem { Text = "Veberage", Value = "3" });
products.Add(new SelectListItem { Text = "Snacks", Value = "4" });
flavours.Add(new SelectListItem { Text = "Select Flavour", Value = "0", Selected = true });
flavours.Add(new SelectListItem { Text = "Sweet", Value = "1" });
flavours.Add(new SelectListItem { Text = "Sour", Value = "2" });
flavours.Add(new SelectListItem { Text = "Spicy", Value = "3" });
var myResult = new
{
ProductList = products,
FlavourList = flavours
};
return Json(myResult, JsonRequestBehavior.AllowGet);
}
}
Let me know if you have any issue running this code. Thanks Premjeet
如果您在运行此代码时遇到任何问题,请告诉我。感谢 Premjeet
回答by asawyer
Return an anonymous object.
返回一个匿名对象。
return Json( new { Result = result, Id = ID } );
I normally do something like this:
我通常做这样的事情:
public enum NoticeTypes
{
Default,
UpdateComplete,
ResponsePending,
Notice,
Error,
Redirect,
WaitAndRetryAttempt
}
public class AjaxJsonResponse
{
public UserNotice Notice { get; set; }
public object Data { get; set; }
private AjaxJsonResponse() { }
public static JsonResult Create(UserNotice Notice,object Data)
{
return new JsonResult()
{
Data = new
{
Notice = Notice,
Data = Data
}
};
}
}
So that I can write my javascript to always expect ajax calls to return data in a certain format.
这样我就可以编写我的 javascript 以始终期望 ajax 调用以某种格式返回数据。
return AjaxResponse.Create(NoticeTypes.UpdateComplete, new
{
Result = result,
Id = ID
});
Now you can do things like an Ajax Complete global handler that can intercept things like Redirector WaitAndRetrybefore the normal handler gets it, and to have a standard way of communicating additional information about the returned data that is the same across your application.
现在,您可以执行诸如 Ajax Complete 全局处理程序之类的操作,该处理程序可以在普通处理程序获取它之前Redirect或WaitAndRetry之前拦截它,并拥有一种标准方式来传达有关在您的应用程序中相同的返回数据的附加信息。
回答by SLaks
You should return an object with multiple properties:
您应该返回具有多个属性的对象:
return Json(new {
result,
ID
});
The JSON serializer will convert C# anonymous types into JSON object literals.
JSON 序列化程序将 C# 匿名类型转换为 JSON 对象文字。
回答by Rajdeep
In Action method :
在行动方法:
Using new keywork
使用新的keywork
var genericResult = new { homeworkData = homework, attachmentData = homeworkAttachment };
var result = this.Json(genericResult, JsonRequestBehavior.AllowGet);
return result;
In jquery side :
在 jquery 方面:
function getHomewrokDetailResponse(dataSent, result) {
if (result && result.homeworkData) {
homeworkId = result.homeworkData.DASH_EMPLOYEE_HOMEWORK_ID;
....
}

