ASP.net MVC Controller Action - how to prevent redirect

asp.net-mvc-3, jquery

Solution

because your code is so. When you click on the button you are calling the `DoSomething` javascript function and inside that you are submitting the form. So it is same as the normal form submit(clicking on the submit button to submit). that is the reason it is redirecting (actually being posted to `DoSomething` action.

If you do not want to navigate away from the current page, you may use `ajax` to do your posting and get result and stay in the same page. So i would make changes to your code like this

1) Get rid of the OnClick event binding from the HTML markup

2) Add this javascript which handles the form submit

$(function(){
  $("#search-frm").submit(e){

   e.preventDefault();  // prevent the default form posting. Let's stay here
   $.post("@Url.Action("DoSomething","MyActions")",$("#search-frm").serialize(), function(data){
          //do something with the response data 
   });

  });     
});

Not sure why return `EmptyResult` from the Action method. You may need to return some valid response which indicates the status of the Action you are trying to perform.

[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something 
   return Json(new 
             { Status= true,
               Message="Succesfully saved"
             });      
}

You may keep a generic `ViewModel` to return such results and use that, instead of dynamically typing like above.

public class OperationStatus
{
  public bool Status  { set;get;}
  public string Message { set;get;}
}

and in your action method

[HttpPost]
public ActionResult DoSomething(string param1,string param2)
{
  //do something 
  var res=new OperationStatus();
  res.Status=true;
  res.Message="Successfully Added";
   return Json(res);      
}

Problem

I have the following in my Action: ``` [AjaxException] public ActionResult DoSomething(sring someParam1, string someParam2) { //do whatever you need to do here, db etc return new EmptyResult(); } ``` in my html ``` <form id="search-frm" name="search-frm" action="@Url.Action("DoSomething", "MyActions")" method="post" > <input type="button" id="search-btn" value="search" class="btn" onclick="DoSomething();return false;" /> <input type="text" name="param1" id="param1" /> <input type="text" name="param2" id="param2" /> </form> ``` in my JS ``` function DoSomething() { $("#search-frm").submit(); return false; } ``` When I click on the button, and after the controller action `DoSomething` is done, I get redirected to `MyActions/DoSomething`. Is there a way to not have that w/o using jquery `$.ajax`? I simply need to do something and not go away from the existing page.

Original source