asp.net mvc 通过 javascript 读取 ViewBag 通用列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17305925/
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
asp.net mvc reading ViewBag generic list via javascript
提问by raranibar
I'm working with asp.net mvc4, How I can read data from ViewBag, my ViewBag is a Generic List, I would like to access the data (viewbag) from javascript.
我正在使用 asp.net mvc4,如何从 ViewBag 读取数据,我的 ViewBag 是一个通用列表,我想从 javascript 访问数据(viewbag)。
I'm passing a generic list from the controller to the view, this list helps me to load a dropdownlist up here works well. Besides loading the dropdownlist I need to access some generic list data so that when the value of the dropdownlist to update a textbox with data from the list
我正在将一个通用列表从控制器传递到视图,这个列表帮助我加载一个下拉列表在这里工作得很好。除了加载下拉列表,我还需要访问一些通用列表数据,以便当下拉列表的值使用列表中的数据更新文本框时
回答by pfluggs11
Technically you ViewBag is a dictionary that can contain a Generic List. It is only available when your page is initially rendered. Thus you can't access it directly from JavaScript. But what you can do is get the list from your ViewBag, serialize it as JSON in Razor and deserialize it in JavaScript.
从技术上讲,您的 ViewBag 是一个可以包含通用列表的字典。它仅在您的页面最初呈现时可用。因此你不能直接从 JavaScript 访问它。但是您可以做的是从您的 ViewBag 中获取列表,在 Razor 中将其序列化为 JSON,然后在 JavaScript 中将其反序列化。
public ActionResult Index(){
//make this whatever list you want
ViewBag.MyList = new ArrayList();
}
This sets a key in the ViewBag dictionary equal to a list of your choosing. Now, we need to serialize it so we can access it in JavaScript.
这将 ViewBag 字典中的键设置为等于您选择的列表。现在,我们需要序列化它,以便我们可以在 JavaScript 中访问它。
var jsonList = '@Html.Raw(Json.Convert(ViewBag.MyList))'
var jsList = JSON.parse(jsonList);
This is a lot of work to just get a list, not to mention, making dependencies in the View for Newtonsoft.Json or whatever serializer you use, and also if memory serves, it is not very efficient. Why not make a request to get the data you need from an API controller which will take care of the serialization for you, resulting in a faster initial page load?
这只是获取列表的工作量很大,更不用说在 Newtonsoft.Json 或您使用的任何序列化程序的视图中创建依赖项,而且如果有内存的话,效率也不是很高。为什么不请求从 API 控制器获取您需要的数据,它会为您处理序列化,从而加快初始页面加载?
Edit: I think what you're looking for is this. You don't need to use JavaScript to achieve what you are asking for. Leverage the power of MVC.
编辑:我想你要找的是这个。您不需要使用 JavaScript 来实现您的要求。利用 MVC 的力量。
回答by Graham
One of the easiest ways to pass data back and forth from your ASP.NET code to your JS layer, is to serialize your objects and then render the serialization into the View as a JS object. Here's an example:
将数据从 ASP.NET 代码来回传递到 JS 层的最简单方法之一是序列化对象,然后将序列化作为 JS 对象呈现到视图中。下面是一个例子:
// helper extension method
public static string ToJSON(this object o)
{
var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return oSerializer.Serialize(o);
}
Inside your controller:
在您的控制器内部:
Viewbag.Foo = myObj.ToJSON();
Then, inside your View, you just spit out the serialized obj as literal JavaScript:
然后,在您的视图中,您只需将序列化的 obj 作为文字 JavaScript 输出:
var json = @Html.Raw(Viewbag.Foo); // mix of Razor and JS here!
When you run it, if you view source, you'll see something like this in that section of the View:
当你运行它时,如果你查看源代码,你会在视图的那个部分看到这样的东西:
var json = {"prop1":true, "arrayItems":[{ "prop1": "dog" }, { "prop": "car" }]}
回答by Andre Calil
DISCLAIMER
免责声明
This is an extremelystraightforward, simple and non-elegant solution. However, it works =)
这是一个非常直接、简单且不优雅的解决方案。但是,它有效=)
Consider this class:
考虑这个类:
public class Something
{
public int Id { get; set; }
public string PropA { get; set; }
public string PropB { get; set; }
}
And this code on your action:
以及关于您的操作的这段代码:
List<Something> list = new List<Something>() {
new Something(){ Id = 1, PropA = "1-A", PropB = "1-B "}
, new Something(){ Id = 2, PropA = "2-A", PropB = "2-B "}
};
ViewBag.Things = list;
Finally, the view:
最后,观点:
<select id="theSelect">
@foreach (Something item in ViewBag.Things)
{
<option value="@item.Id">@item.PropA</option>
}
</select>
<input type="text" id="selectedPropB" readonly />
<div style="display: none;">
@foreach (Something item in ViewBag.Things)
{
<span id="[email protected]">@item.PropB</span>
}
</div>
<script type="text/javascript">
$(function () {
$('#theSelect').on('change', function () {
var id = $(this).val();
$('#selectedPropB').val($('#propb-'+id).html());
});
});
</script>
Notes:
笔记:
- I'd rather be using a viewmodelinstead of the
ViewBag
, because reasons. Anyway, it's up to you - I'm sure you can find better solutions if you work with knockout and so on. Anyway, as I said, this works
- 我宁愿使用视图模型而不是
ViewBag
,因为原因。无论如何,这取决于你 - 如果您使用淘汰赛等方式,我相信您可以找到更好的解决方案。无论如何,正如我所说,这有效
回答by ecasper
<script type="text/javascript">
var jsList= @Html.Raw(Json.Encode(@ViewBag.GenericList));
</script>