0

I have a Home controller whose view has a button.I want to call a controller named SearchSpace on button click.

View :

  <script type="text/javascript">

    var data = { "id": "1" }

    function search() {
        alert("hello" + JSON.stringify(data));
            $.ajax({
             url: '/SearchSpace/searchSpace',
             type: 'POST',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (returnPayload) {
                console && console.log("request succeeded");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console && console.log("request failed");
            }

        });

    }
 </script>

Controller

   [HttpGet]
    public ActionResult searchSpace()
    {
 return View();
    }

    [HttpPost]
    public ActionResult searchSpace(SearchSpace search)
    {
        //code 
           return View();
    }

Route Config

         public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

alert is calling but it is not moving to SearchSpace Controller.. Please help me.

5
  • what do you mean by "not moving"? And is your error function being called? Commented Jun 7, 2014 at 14:48
  • No error message is displayed.moving meaning calling that controller action Commented Jun 7, 2014 at 14:50
  • have you tried with the alert after the ajax call? Commented Jun 7, 2014 at 14:52
  • Do you have searchSpace action in SearchSpace controller that handle http post request? If so, would be better if you show us that action method. Commented Jun 7, 2014 at 15:01
  • Also, would be better if you show us RouteConfig Class, too. Commented Jun 7, 2014 at 15:10

2 Answers 2

1

try this

      <button id="click"><a href="/Home/About">Click me</a>
      </button>
Sign up to request clarification or add additional context in comments.

2 Comments

tried this <button id="click"><a href="@Url.Content("~/Controllers/Account/Register")">Click me</a>.but resorce not found error.
I tried, above code, it create button and once u click it will redirect u to about us page, if u pass root sign u need to pass extension of tht page also. Better use the controller/ view name
0

Problem is with data type that jQuery.ajax() is expect, since you assign dataType property with json. From jQuery API documentation:

dataType (default: Intelligent Guess (xml, json, script, or html)) Type: String The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

..."json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

There are at least 2 ways to solve the problem:

First, Omit dataType property:

$.ajax({
    url: '/SearchSpace/searchSpace',
    type: 'POST',
    contentType: 'application/json',
    //dataType: "json", << delete this line or comment it
    data: JSON.stringify(data),
    success: function (data) {
        console && console.log(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console && console.log("request failed");
    }
});

Second, return JSON type data from response:

[HttpPost]
public ActionResult searchSpace(int? id)
{
    if (Request.IsAjaxRequest() && id != null)
    {
        return Json(new { data = "Requested data is: " + id.ToString() });
    }

    return View();
}

2 Comments

I tried both methods but unable to call controller action method
@Wasfa Did you try to debug your code? add brake point in to the action method and then look, if that action method is called after clicking the button.

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.