0

Trying to invoke a method on my controller from my index.cshtml file.

Html.BeginForm("Index", "Default", FormMethod.Get);

Where index is my method name, default is the controller and get is self explanatory. When I right click on "Index" and go to implementation it takes me to the method in my controller. However, when I debug the code it won't step into the Controller method and goes to the next line of code despite breakpoints obviously being in place and debug tool options set up correctly.

Also tried

<form method="get" action='@Url.Action("Index", "Default")'></form>

Similarly can't step into the controller.

How can I correctly invoke my controller method?

8
  • 1
    Please also post your controller code Commented Oct 22, 2019 at 21:11
  • What do you mean by "invoke"? Just putting Html.BeginForm in your code doesn't execute your controller, rather, it renders a <form /> tag in the generated HTML. Commented Oct 22, 2019 at 21:30
  • Did you mean that there is a form in your index.cshtml,and you want to get into your index action in Default Controller without clicking button when your page loads? Commented Oct 23, 2019 at 8:15
  • And what is your form like?Did you want to pass data to the controller? Commented Oct 23, 2019 at 8:16
  • By "invoke" I mean I want to call the controller and therefore I expect to step into the controller code. @Rena yes, on page load (without any interaction from the user) I want to put some code in the index.cshtml file which will get into my index action in the default controller. No data is required to pass to the controller. The controller will not accept any parameters. I just need to know how to call the controller from the index.cshtml (ignore all the code I've put above I do not need to use a form tag, I do not need to submit any data, just trying to get it to work and tried form). Commented Oct 23, 2019 at 18:59

2 Answers 2

1

Form

An HTML <form> needs a submit button (and usually some controls) before it will call the controller action. It looks like the form in your example is empty.

You haven't shown the controller, but let's assume you want to pass a string to the controller action, maybe to search or filter:

public ActionResult Index(string searchTerm)
{
    // do something with parameters then return view
    return View();
}

Instead of this in your view:

Html.BeginForm("Index", "Default", FormMethod.Get);    // empty form

It should be something like this:

@Html.BeginForm("Index", "Default", FormMethod.Get) 
{
    // add controls here, what parameters are you passing? 
    @Html.TextBox("SearchTerm")
    <input type="submit" value="Search" />
}

Tag Helpers

Since you're using ASP.Net-Core you can take advantage of tag helpers which allow you to write code in a more HTML like manner. I encourage you to read Tag Helpers in forms in ASP.NET Core. One way the above could be written using tag helpers is:

<form asp-action="Index" asp-controller="Default" method="get">
    <input type="text" name="SearchTerm" />
    <button>Search</button>
</form>

ActionLink

Perhaps you want to create a hyperlink to Default/Index? In that case, use the @Html.ActionLink helper:

@Html.ActionLink("go to this link", "Index", "Default")

Which will create a regular anchor <a>:

<a href="/Default">go to this link</a>

Tag Helper version

<a asp-action="Index" asp-controller="Default" >Click this link</a>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the very comprehensive answer. Yes, the form is empty as I just want to invoke the code in the controller on page load, there are no buttons required to initiate the call of the controller. It sounds like form is not what I should be using then. I was putting too much logic into the cshtml file, so thought it best to put it behind a controller. Therefore it looks like form is not what i want, what else should i use? The controller will not accept any parameters, on page loads the controller needs to be called and the return data from the controller displayed on that page. Thank
The code in the controller is invoked when someone navigates to that page. Will users browse to the page default/index or will it be called from a different page? Do you just want to get the data? If that's the case then it sounds like you might want to look into ajax which can be used to send asynchronous requests to the controller. It's hard to say what you should do without more context @Eloise
Yes, the users will browse to the page default/index and the code is in the index.cshtml file. As soon as the page loads i want the code in the cshtml file to invoke the controller (with no interaction required from the user). The controller will not accept any parameters. The controller will then get some data using entity framework and then return the data to the index.cshtml in order to display to the user.
0

When you load index.cshtml,it would get into index action by default.You need to return model in your index action.

Here is a simple demo like below:

1.Model:

public class Test
{
    public int ID { get; set; }
    public string Title { get; set; }
}

2.Index.cshtml:

@model IEnumerable<TestModel>
<h1>Index</h1>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>            
        </tr>
}
    </tbody>
</table>

3.Index action:

public class TestModelsController : Controller
{
    private readonly MyDbContext _context;

    public TestModelsController(MyDbContext context)
    {
        _context = context;
    }

    // GET: TestModels
    public async Task<IActionResult> Index()
    {
        var model = await _context.TestModel.ToListAsync();
        return View(model);
    }
}

Reference: Passing data to views

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.