简体   繁体   中英

Call a different Controller action from view of a controller though javascript

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.

try this

      <button id="click"><a href="/Home/About">Click me</a>
      </button>

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM