[英]MVC4 - How to call controller method from razor view
我是MVC的新手,有人可以幫助我並解釋如何從視圖中調用控制器方法。
我有HomeController,里面有我的方法ShowFileContent()。
[HttpPost]
public ActionResult ShowFileContent()
{
string filepath = Server.MapPath("\\Files\\Columns.txt");
try
{
var lines = System.IO.File.ReadAllLines(filepath);
foreach (var line in lines)
{
ViewBag.FileContent += line + "\n";
}
}
catch (Exception exc)
{
ViewBag.FileContent = "File not found";
}
return View();
}
在內部視圖中,我試圖用下面的代碼調用此方法,但它不起作用。
@using (Html.BeginForm("ShowFileContent", "Home"))
{
<input type="submit" value="Show File" style='width:300px'/>
}
<h2>@Html.Raw(ViewBag.FileContent.Replace("\n", "</br>"))</h2>
我收到錯誤:找不到視圖'ShowFileContent'或其主人,或者沒有視圖引擎支持搜索的位置。
我做錯了什么,從剃刀視圖調用方法的最佳方法是什么?
您可以使用內置的Action方法從View調用操作。
@Html.Action("actionName", "ControllerName")
這聽起來像是打破你的
return View();
如果你不告訴它去哪里它認為視圖被稱為與你的動作相同。
所以試試吧
return View("Name of your view");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.