Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 - How to call controller method from razor view

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 ?

like image 658
msharank Avatar asked Mar 05 '14 21:03

msharank


People also ask

How do you call a method from razor page?

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.


1 Answers

You can use inbuilt Action method to call action from View.

@Html.Action("actionName", "ControllerName")
like image 70
Sachin Kalia Avatar answered Oct 14 '22 07:10

Sachin Kalia