MVC4-如何从剃刀视图调用控制器方法 [英] MVC4 - How to call controller method from razor view
问题描述
我是MVC的新手,有人可以帮助我,并从视图中解释如何调用控制器方法.
i am new with MVC, can someone please help me and explain how to call controller method from a view.
我有HomeController,里面有ShowFileContent()方法.
I have HomeController and inside it I have method 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();
}
在内部视图中,我尝试使用下面的代码调用此方法,但是它不起作用.
Inside view I've tried to call this method with code bellow but it does not work.
@using (Html.BeginForm("ShowFileContent", "Home"))
{
<input type="submit" value="Show File" style='width:300px'/>
}
<h2>@Html.Raw(ViewBag.FileContent.Replace("\n", "</br>"))</h2>
我得到错误:找不到"ShowFileContent"视图或其主视图,或者没有视图引擎支持搜索到的位置.
I get error: The view 'ShowFileContent' or its master was not found or no view engine supports the searched locations.
我做错了什么?从剃刀视图调用方法的最佳方法是什么?
What i am doing wrong and whats the best way to call methods from razor view ?
推荐答案
在我看来,它像是在破坏您的
It sounds to me like its breaking on your
return View();
如果您不告诉它去哪里,它会认为该视图与您的操作相同.
If you dont tell it where to go it thinks the view is called the same as your action.
所以尝试
return View("Name of your view");
这篇关于MVC4-如何从剃刀视图调用控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!