我是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>
我收到错误:未找到视图"显示文件内容"或其主节点,或者没有视图引擎支持搜索的位置。
我做错了什么,从剃刀视图调用方法的最佳方法是什么?
可以使用内置的 Action 方法从 View 调用操作。
@Html.Action("actionName", "ControllerName")
在我看来,
它打破了你的
return View();
如果你不告诉它去哪里,它会认为视图与你的操作相同。
所以尝试
return View("Name of your view");