Wykonanie prostego wywołania Ajax do kontrolera w asp.net mvc
Próbuję zacząć od ASP.NET połączenia MVC Ajax.
Kontroler:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
Widok:
<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
Muszę tylko wydrukować alert z metodą kontrolera zwracającą dane. Powyższy kod po prostu wydrukuj "chamara" na moim zdaniem. Alarm nie strzela.
UPDATE
Zmodyfikowałem mój kontroler jak poniżej i zaczął działać. Nie mam pojęcia, dlaczego to teraz działa. Niech ktoś wyjaśni. Parametr "a" nie ma związku z i dodałem go, ponieważ nie mogę dodać dwóch metod o tej samej nazwie metody i parametrach.Myślę, że to może nie być rozwiązanie, ale jego działanie
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
9 answers
Po aktualizacji, którą wykonałeś,
- pierwsze wywołanie akcji FirstAjax z domyślnym żądaniem HttpGet i renderuje pusty Widok Html . (Wcześniej tego nie miałeś)
- później po załadowaniu elementów DOM tego widoku Twoje wywołanie Ajax zostanie zwolnione i wyświetli alert.
Wcześniej zwracałeś tylko JSON do przeglądarki bez renderowania HTML. Teraz ma renderowany widok HTML, w którym może pobrać dane JSON.
Nie możesz bezpośrednio renderować JSONA zwykłe dane, a nie HTML.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-25 06:12:55
Usuń atrybut data, ponieważ nie jesteś POSTING
niczym dla serwera (Twój kontroler nie oczekuje żadnych parametrów).
I w Twojej metodzie AJAX możesz używać Razor
i używać @Url.Action
zamiast statycznego ciągu znaków:
$.ajax({
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Z Twojej aktualizacji:
$.ajax({
type: "POST",
url: '@Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-20 05:23:28
Użyj brzytwy do dynamicznej zmiany adresu URL, wywołując akcję w następujący sposób:
$.ajax({
type: "POST",
url: '@Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-02 11:43:38
To dla Twojego pytania o aktualizację.
Ponieważ nie możesz mieć dwóch metod o tej samej nazwie i podpisie, musisz użyć atrybutu ActionName:
Aktualizacja:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
I proszę odnieść się do tego linku, aby uzyskać dalsze informacje o tym, jak metoda staje się działaniem. Bardzo dobre referencje.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-25 09:34:51
Po pierwsze nie ma potrzeby posiadania dwóch różnych wersji bibliotek jquery na jednej stronie, albo "1.9.1 " lub" 2.0.0 " wystarczy, aby wywołania ajax działały..
Oto twój kod kontrolera:
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Tak powinien wyglądać twój Widok:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "../../Home/FirstAjax",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
});
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-06 08:22:16
Jeśli po prostu trzeba nacisnąć C # metoda na w wywołaniu Ajax wystarczy przekazać dwa Typ sprawy i url jeśli żądanie jest get to wystarczy podać tylko adres url. postępuj zgodnie z poniższym kodem, działa dobrze.
C# Code
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Java Script Code if Get Request
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
Java Script Code if Post Request and also [HttpGet] to [HttpPost]
$.ajax({
url: 'home/FirstAjax',
type:'POST',
success: function(responce){ alert(responce)},
error: function(responce){ alert(responce)}
});
Uwaga: Jeśli najpierw używasz tego samego kontrolera, w którym twój kontroler widoku, to nie ma potrzeby podawania nazwy kontrolera w adresie url. jak url: 'FirstAjax',
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 09:34:14
Widok;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Metoda Kontrolera;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-22 06:01:21
Zamiast url: serviceURL,
użycie
url: '<%= serviceURL%>',
Przekazujesz 2 parametry do successFunc?
function successFunc(data)
{
alert(data);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-24 07:55:22
Dodaj "JsonValueProviderFactory" w global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-24 09:07:06