i'm using this code to get a partial view from the server ot put it in a div
$.ajax(
{
type: "POST",
url: "MyControler/MyAction",
success: function (result) {
$('#partialView').html(result);
},
error: function (req, status, error) {
alert("Coudn't load partial view");
}
});
now i would like to do the same thing but i'd call a simple methode returning a string and put the result in a textbox
$.ajax(
{
type: "POST",
url: "MyControler/MyMethod",
success: function (result) {
$('#myTextBox').html(result);
},
error: function (req, status, error) {
alert("Coudn't load partial view");
}
});
the methode would be like that
public string MyMethod()
{
re开发者_如何学Goturning "hello";
}
obviously it doesn't work but is there a way to make it work ?? is there an attribute i should use for the methode
thanks in advance
ps:
from what i red in the first answer i tried this but it doesn't work
public ActionResult Hello()
{
return Content("Hi there!");
}
is there something wrong with the ajax call ??
$.ajax(
{
type: "POST",
url: "MyControler/Hello",
success: function (result) {
$('#myTextBox').html(result);
},
error: function (req, status, error) {
alert("Coudn't load partial view");
}
});
ps
I wanted to try on a clean project and it worked fine using a simple method returning a string
since it worked i tried to implement it to my project but it seems it only works from the starting page set up in the global.asax file any idea what i should do to make it work in every pages ???
You are making an HttpPost call. So make sure your Action method is decorated with HttpPost
attribute. Also always try to use Url.Action
HTML Helper method for the path to the action method.
The below code should work, assuming you have the Hello
Action method present in MMyControlerController
.
$.ajax(
{
type: "POST",
url: "@Url.Action("Hello","MyControler")",
success: function (result) {
alert("result from server "+result);
$('#myTextBox').html(result);
},
error: function (req, status, error) {
alert("Coudn't load partial view");
}
});
Your action method
[HttpPost]
public ActionResult Hello()
{
return Content("This is String Content");
}
I guess You should use following
$('#myTextBox').attr('value',result);
instead of
$('#myTextBox').html(result);
You want to return a string from that method, yes, but what you want is an ActionResult that returns the string Check the following question and answer on StackOverflow.
In MVC, how do I return a string result?
It's better to use the Url.Action
method for cases when you're running under a virtual directory or sub-domain. The Action method will create the correct Url.
Apart from that, it looks like you're POSTing to the site, so have you added the HttpPost
attribute to your action?
精彩评论