更新时间:2023-02-25 21:50:16
要渲染直接在控制器动作,你可以试试:
To render directly a controller action, you can try :
@ {Html.RenderAction(动作,控制器); }
@{ Html.RenderAction(Action, Controller); }
要调用你的控制器动作,应该返回一个字符串您的内容。
To invoke your controller action that should be returning a string with your content.
[HttpGet]
public string Action(int id)
{
return your context in here
}
不过,我认为这是清洁剂中添加一个Ajax操作返回的数据构建的选择,并有结果后,使用jquery解决方案添加类
However I think it's cleaner to add an Ajax action returning the data for building the select and after having the results, using jquery solution for adding a class (which can be returned in the AJAX response itself)
编辑:澄清:
假设你有项目的集合如下:
Assuming you've got a collection of Item as follows:
class Item {
public int Value { get; set; }
public string CssClass { get; set; }
public string Description{ get; set; }
}
private const string EMPTY_OPTION = "<option value=''></option>";
[HttpGet]
public string Action(int id)
{
// Load a collection with all your option's related data
IQueryable data = LoadSomethingFromDbOrWherever(id);
// Build output
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<select id='foo' name='foo'>");
sb.AppendFormat(EMPTY_OPTION);
foreach (Item b in data)
{
sb.AppendFormat("<option value='{0}' class='{1}'>{2}</option>",
b.Value, b.CssClass, b.Description);
}
sb.AppendFormat("</select>");
return sb.ToString();
}
阿贾克斯选项:
for ajax option:
[HttpGet]
public JsonResult Action(int id)
{
//same as above, obtain a collection
// Load a collection with all your option's related data
IQueryable data = LoadSomethingFromDbOrWherever(id);
var jsonData = new
{
from c in data
select new
{
Value= c.Value,
CssClass = c.CssClass,
Description = c.Desription
}).ToArray()
};
return Json(jsonData);
}
通过$就调用这一点,并在回调你必须包含所有数据的JavaScript对象,然后使用jQuery建立的选择选项。
Call this via $.ajax and in the callback you'll have a javascript object containing all your data, then use jQuery to build up the select options.
问候