C# 4.0 如何将现有视图附加到控制器操作?
如何将现有视图附加到动作? 我的意思是,我已经把这个视图附加到了一个动作上,但我想附加到第二个动作上 例如: 我有一个名为Index的操作和一个视图,名称相同,附加到它上,右键单击,添加视图…,但现在,如何附加到第二个?假设一个名为Index2的操作,如何实现 代码如下:C# 4.0 如何将现有视图附加到控制器操作?,c#-4.0,asp.net-mvc-4,C# 4.0,Asp.net Mvc 4,如何将现有视图附加到动作? 我的意思是,我已经把这个视图附加到了一个动作上,但我想附加到第二个动作上 例如: 我有一个名为Index的操作和一个视图,名称相同,附加到它上,右键单击,添加视图…,但现在,如何附加到第二个?假设一个名为Index2的操作,如何实现 代码如下: //this Action has Index View attached public ActionResult Index(int? EntryId) { Entry entry = Entry.GetNext(En
//this Action has Index View attached
public ActionResult Index(int? EntryId)
{
Entry entry = Entry.GetNext(EntryId);
return View(entry);
}
//I want this view Attached to the Index view...
[HttpPost]
public ActionResult Rewind(Entry entry)//...so the model will not be null
{
//Code here
return View(entry);
}
我在谷歌上搜索,找不到合适的答案。。。
这是可能的?您不能将操作“附加”到视图,但您可以使用Controller.view
方法定义希望操作方法返回的视图
public ActionResult MyView() {
return View(); //this will return MyView.cshtml
}
public ActionResult TestJsonContent() {
return View("anotherView");
}
这有帮助吗?可以使用视图重载指定不同的视图:
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
ViewBag.Message = "Hello I'm Mr. Index";
return View();
}
//
// GET: /Test/Index2
public ActionResult Index2()
{
ViewBag.Message = "Hello I'm not Mr. Index, but I get that a lot";
return View("Index");
}
}
以下是视图(Index.cshtml):
@{
ViewBag.Title=“Index”;
}
指数
@查看包。留言
当我右键单击操作时,关联菜单会显示“添加视图”选项,没关系。因此,我无法将同一视图添加到另一个操作?您可以手动将新视图添加到项目中,然后使用上面的代码将其返回。我不想添加新视图,我想将现有视图与另一个名为不同的操作重新使用…好的,只需使用返回视图重载返回视图(“anyViewYouWant”);您还必须传递模型:返回视图(“/Views/yAnotherView.cshtml”,yourModel);在您的示例中,它将是返回视图(“索引”,条目);事实上,不是。。。我需要将模型作为参数传递给操作。我的意思是您可以替换//code here
,返回视图(条目)下的行代码>在代码中使用返回视图(“索引”,条目)代码>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>@ViewBag.Message</p>