简体   繁体   中英

Call ASP.NET C# Controller Method from Javascript

I have a var toto in a javascript file. And I want to call a C# Controller Method who return a string and of course assign the resulted string to toto.
I tried some ways to achieve this but nothing seems to work.
Somebody can explain me the simpliest way to achieve that ? It's a Windows Azure project.

Many Thanks !

You could use AJAX. For example with jQuery you could use the $.getJSON method to send an AJAX request top a controller action that returns a JSON encoded result and inside the success callback use the results:

$.getJSON('/home/someaction', function(result) {
    var toto = result.SomeValue;
    alert(toto);
});

and the controller action:

public ActionResult SomeAction() 
{
    return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}

You have to use JSON:

Controler

public class PersonController : Controller
{
   [HttpPost]
   public JsonResult Create(Person person)
   {
      return Json(person); //dummy example, just serialize back the received Person object
   }
}

Javascript

$.ajax({
   type: "POST",
   url: "/person/create",
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: jsonData,
   success: function (result){
      console.log(result); //log to the console to see whether it worked
   },
   error: function (error){
      alert("There was an error posting the data to the server: " + error.responseText);
   }
});

Read more: http://blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

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