Invoke Action Method from Clicking a button in ASP

2019-07-26 19:37发布

问题:

I want to know if I can call a method in the controller when a button is clicked.

I have a view called home and when the view is loaded, it invokes the Index action method in the controller. I have a Button (HTML or ASP.NET) called LoadData. When I click the button, I need to load some data in the same view called Home.

How do I do that?

回答1:

With buttons, it has to involve JQuery or JavaScript to make a call to get the data from the server, if you want to do it in AJAX form. But in its simplest form, doing:

<% Html.BeginForm("Action", "Controller"); %>

 <!--Form values in here-->

 <input type="submit" />

<% Html.EndForm(); %>

Will invoke your action method and invoke a postback. There is an AJAX option in the System.Web.Mvc.Ajax to use an AjaxForm with AJAX options for doing the postback async, and it's easy to setup. I tend to use JQuery instead personally.

HTH.



回答2:

To do this using a simple post, you just need to post to the URL at which the controller method exists.

For example, following the standard routes setup in your global.asax "{controller}/{action}/{id}"

If you have a controller method inside your HomeController class called "LoadData" then you'd access it at the URL:

/Home/LoadData

This is the URL you'd enter into your forms action attribute.

You can also hit this URL using an AJAX request in order to load data into the same page you're on without any postback.

Using jQuery you could do something like:

$('#myForm').submit(function() {
                   $.post(
                            this.action,{params},
                            function(data){ // do something with return info }
                  }


回答3:

You Define two action one for show the empty view and one for populating the view with a list :

public ViewResult Empty()
    {
        var products = productsRepository.Products.Where(x => x.ProductID == -1);
        return View();
    }

and :

public ViewResult ListAll()
    {
        var products = productsRepository.Products;
        return View("Empty", products);
    }

and in your view Empty.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<DomainModel.Entities.Product>>" %>

Empty

<h2>Empty</h2>

<table>
    <tr>
        <th></th>
        <th>
            ProductID
        </th>
        <th>
            Name
        </th>
        <th>
            Description
        </th>
        <th>
            Price
        </th>
        <th>
            Category
        </th>
        <th>
            ImageMimeType
        </th>
        <th>
            Error
        </th>
    </tr>

<% if (Model != null) 
   {
       foreach (var item in Model)
       { %>

    <tr>
        <td>
            <%= Html.ActionLink("Edit", "Edit", new { id = item.ProductID })%> |
            <%= Html.ActionLink("Details", "Details", new { id = item.ProductID })%>
        </td>
        <td>
            <%= Html.Encode(item.ProductID)%>
        </td>
        <td>
            <%= Html.Encode(item.Name)%>
        </td>
        <td>
            <%= Html.Encode(item.Description)%>
        </td>
        <td>
            <%= Html.Encode(String.Format("{0:F}", item.Price))%>
        </td>
        <td>
            <%= Html.Encode(item.Category)%>
        </td>
        <td>
            <%= Html.Encode(item.ImageMimeType)%>
        </td>
        <td>
            <%= Html.Encode(item.Error)%>
        </td>
    </tr>

<% }
   }%>

</table>

<p>
    <%= Html.ActionLink("List Products", "ListAll")%>

</p>

hope this helps



回答4:

You've to write your Controller as follows.

public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult FetchData()
    {
        return Content("Some data...");
    }

}

And call the desired action as follows.

<% using (Ajax.BeginForm("FetchData", new AjaxOptions() { UpdateTargetId = "ContentPlaceHolder", HttpMethod = "Post" }))
   { %>
<div id="ContentPlaceHolder"></div>
<input type="submit" value="Fetch Data" />
<% } %>

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>