如何从控制器指定返回视图?

Max*_*Max 1 c# asp.net-mvc

那是我的控制器:

public ActionResult LabPreparation(int? id)
{
    if (id == null) return new HttpNotFoundResult();

    var lab = db.Labs.Find(id);
    if (lab == null) return HttpNotFound();

    return View(lab);
}
Run Code Online (Sandbox Code Playgroud)
<button type="button" class="btn btn-default" onclick="location.href='@Url.Action("LabPreparation", "Lab", new {id = item.Id})'">Preparation</button>
Run Code Online (Sandbox Code Playgroud)

实验室是一个模型,每个实验室都有不同的视图.如何指定控制器应返回特殊实验室的视图?

L-F*_*our 6

指定应使用的视图,例如:

 return View("viewname", lab);
Run Code Online (Sandbox Code Playgroud)

如果视图位于其他文件夹中,则可以使用完整路径:

 return View("~/Views/Folder/ViewName.aspx").
Run Code Online (Sandbox Code Playgroud)

编辑:

为了确定要显示的视图,您可以创建一个将ID链接到视图名称的词典:

 var dictionary = new Dictionary<int, string>();
 dictionary.Add("1", "ViewName.aspx");
 etc...
Run Code Online (Sandbox Code Playgroud)

并使用如下:

 return View(dictionary[id], lab);
Run Code Online (Sandbox Code Playgroud)

(并添加一些异常处理,当然,例如,如果ID不存在)