i am new with MVC, can someone please help me and explain how to call controller method from a view.
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>
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 ?
Razor pages have handler-methods which are HTTP verbs. So to call a method from your page you need to put On followed by the http verb you want then your method name . And in your view pass the name to the asp-page-handler without the OnPost or OnGet prefix or Async suffix.
You can use inbuilt Action method to call action from View.
@Html.Action("actionName", "ControllerName")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With