1

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 !

4
  • 3
    What exactly did you try already? What didnt seem to work? Did you try ajax? Commented May 30, 2012 at 7:42
  • I tried the two code below but it doesn't work, I don't understand. There's no DialogBox... Commented May 30, 2012 at 8:24
  • I am also facing the same problem. BUt my javascript on master page or lyaoutwithmenu file. Did you figure it out? Commented Jun 21, 2012 at 18:55
  • I figured out by using fiddler that I was missing something in the Url. Commented Jun 21, 2012 at 20:04

2 Answers 2

7

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);
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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.