Search code examples
c#asp.net-mvcpostbackasp.net-mvc-5actionlink

MVC call method on click with / without postback


I have a question regarding the calling method from view.

Basically on my view I have 2 links:

1 link : When I click on it, some method should be called and executed, but nothing should change on webpage, so no postback.

2 link: When I click on it, some method should happen and postback can happen, on the same page

In controller I have:

public ActionResult FirstMethod(){ return View();}
public ActionResult SecondMethod(){ return View();}

In view:

@Html.ActionLink("Action 1", "FirstMethod", "Controller");
@Html.ActionLink("Action 2", "SecondMethod", "Controller");

So when I click on both action happens but then i get an error saying cannot find FirstMethod.chtml ..

So is this possible to have one method with postback and another one without? And how to return to the same page ... and not try to get FirstMethod.chtml ..


Solution

  • Following solution is based on AJAX -

    Controller -

        public class DemoController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpGet]
            public ActionResult CallMe()
            {
                return new ContentResult() { Content = "This is Demo " };
            }
    }
    

    Index.cshtml -

    <h2>Index</h2>
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#Click").click(function () {
                $.ajax({
                    url: "/Demo/CallMe",
                    type: "GET",
                error: function (response) {
                        alert(response);
                },
                success: function (response) {
                    alert(response);
                }
            });
            });
        })
    </script>
    
    <input type="button" value="Click" id="Click" />
    

    First navigate to /demo/Index, that will display the page with above markup with a button in the page. And when we click on the Click button, we have -

    enter image description here