MVC4 - 如何从剃刀视图调用控制器方法

msh*_*ank 7 c# asp.net-mvc razor asp.net-mvc-4

我是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();
} 
Run Code Online (Sandbox Code Playgroud)

在内部视图中,我试图用下面的代码调用此方法,但它不起作用.

@using (Html.BeginForm("ShowFileContent", "Home"))
{
    <input type="submit" value="Show File" style='width:300px'/>        
}
<h2>@Html.Raw(ViewBag.FileContent.Replace("\n", "</br>"))</h2>
Run Code Online (Sandbox Code Playgroud)

我收到错误:找不到视图'ShowFileContent'或其主人,或者没有视图引擎支持搜索的位置.

我做错了什么,从剃刀视图调用方法的最佳方法是什么?

Sac*_*lia 7

您可以使用内置的Action方法从View调用操作.

@Html.Action("actionName", "ControllerName")
Run Code Online (Sandbox Code Playgroud)


Rya*_*ter 3

在我看来,这就像它打破了你的

 return View();
Run Code Online (Sandbox Code Playgroud)

如果你不告诉它去哪里,它会认为视图的名称与你的操作的名称相同。

所以改为尝试

return View("Name of your view");
Run Code Online (Sandbox Code Playgroud)