将 JSON 数据从控制器操作传递到剃刀视图
我想知道如何将数据从控制器传递到 mvc3 razor 中的视图。 该视图位于 .cshtml 文件中。 我在控制器中有一个变量,我在其中存储需要推送到视图中的列表框控件的数据。
var results = data.Select(item => new { id = item, label = item.Value, value = item.Key });
这样做:
return Json(results, JsonRequestBehavior.AllowGet);
只给我一个弹出窗口,其中包含需要推送到列表框的数据:
在视图列表框中驻留在手风琴控件中:
<div id="accordion">
@{int i=0;}
@foreach (var item in Model.Parameters)
{
<h3><a href="#">@Html.LabelFor(m => item.Name, item.Prompt)</a></h3>
<div>
<div class="editor-field">
<select multiple id="@("Select" +item.Name)" name="@("Select" +item.Name)"></select>
</div>
</div>
i++;
}
</div>
所以,我想知道我应该怎么做才能将项目推送到列表框,而不是显示控件的弹出窗口
MVC 初学者,感谢您的理解。 预先感谢,Laziale
编辑:Json 格式输出
{System.Linq.Enumerable.WhereSelectListIterator<System.Collections.Generic.KeyValuePair<string,string>,<>f__AnonymousType1<System.Collections.Generic.KeyValuePair<string,string>,string,string>>}
I would like to know how can I pass data from controller to view in mvc3 razor.
The view is in .cshtml file.
I have a variable in the controller where I am storing the data I need to push to the listbox control in the view.
var results = data.Select(item => new { id = item, label = item.Value, value = item.Key });
Doing this:
return Json(results, JsonRequestBehavior.AllowGet);
Gives me only a popup with the data which needs to be pushed to the listbox:
In the view the listbox resides in accordion control:
<div id="accordion">
@{int i=0;}
@foreach (var item in Model.Parameters)
{
<h3><a href="#">@Html.LabelFor(m => item.Name, item.Prompt)</a></h3>
<div>
<div class="editor-field">
<select multiple id="@("Select" +item.Name)" name="@("Select" +item.Name)"></select>
</div>
</div>
i++;
}
</div>
So, I would like to know what should I do to push the items to the listbox instead of showing a popup for the control
Beginner in MVC, Thanks for your understanding.
Thanks in advance, Laziale
EDIT: Json format output
{System.Linq.Enumerable.WhereSelectListIterator<System.Collections.Generic.KeyValuePair<string,string>,<>f__AnonymousType1<System.Collections.Generic.KeyValuePair<string,string>,string,string>>}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

将 JSON 返回到您的 razor 视图可能不是最好的方法。我建议使用 viewModel,它本身就是 ac# 类。
您的视图代码:
如果您被迫使用从操作返回的 JSON 对象,那么您需要先对其进行反序列化,然后再使用该对象。你可以阅读这篇文章 http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx 了解如何将 JSON 解析为 ac# 动态对象。
让我知道这是否有帮助。
returning JSON to your razor view is probably not the best method. I would suggest use a viewModel which is a c# class by itself.
Your view code:
If you are forced to work with a JSON object that is returned from your action then you need to deserialize it first and then work with that object. you can read this post http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx on how to parse JSON to a c# dynamic object.
Let me know if that helps.