admin管理员组文章数量:1361787
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 !
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 !
Share Improve this question asked May 30, 2012 at 7:40 MaTMaT 1,6063 gold badges34 silver badges66 bronze badges 4- 3 What exactly did you try already? What didnt seem to work? Did you try ajax? – papaiatis 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... – MaT 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? – alice7 Commented Jun 21, 2012 at 18:55
- I figured out by using fiddler that I was missing something in the Url. – alice7 Commented Jun 21, 2012 at 20:04
2 Answers
Reset to default 7You 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./2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34
本文标签: Call ASPNET C Controller Method from JavascriptStack Overflow
版权声明:本文标题:Call ASP.NET C# Controller Method from Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743873281a2553864.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论