Я пытаюсь вызвать контроллер, нажав кнопку. Моя цель - получать значения даты из представления и вызывать другие данные от контроллера, но ajax-вещь так раздражает меня. Поэтому я сделал тестовый, но он все еще не работает.вызов диспетчера ajax ASP.Net MVC
Я следил за несколькими учебниками и вопросами SO, и именно так я решил вызвать метод контроллера (testtest) с помощью javascript ajax-функций. Вот the tutorial, что я последовал в последний раз.
$(document).ready(function() {
$('#btnSelectDate').click(function() {
alert("working");
var text= $('#txtStartDateI').val();
var button= $('#btnSelectDate').val();
alert(text + " " + button);
$.ajax({
url: "/Home/testtest",
type: "post",
datatype: "text",
data: { btnSelectDate: button, txtStartDate: text},
success: function (data) {
('#testarea').html(data);
},
error: function() {
$('#testarea').html("ERROR");
}
});
});
});
И это метод «testtest»:
[HttpPost]
public string testtest(string btnSelectDate,string txtStartDate) {
return ("btnValue : " + btnSelectDate + "\ntxtStartDate: " + txtStartDate);
}
При нажатии кнопки, сигналы работают, но это не вызывает метод «testtest» в HomeController. Я устанавливаю точки останова в контроллере, но он не проходит. После того, как он отобразит диалоговое окно предупреждения, вся страница начнет мигать и ничего не изменилось. Я попытался сделать <div id="testarea"></div>
получить текстовое значение.
Я пробовал различные формы URL, как:
url: '@Url.Action("testtest","Home")'
url: 'localhost/Home/testtest'
Но до сих пор не попал в контроллер.
Требуется ли для ajax добавлять специальные скрипты? (Я думаю, я добавил сценарии ajax, так как есть некоторые ссылки, содержащие «ajax».) Или мне нужно сделать что-то особенное, чтобы вызвать метод с помощью ajax?
Ребенок - это весь мой код. Это мой контроллер «Home»:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace haha.Controllers {
public class HomeController : Controller {
public ActionResult View() {
return View("View");
}
[HttpPost]
public string testtest(string btnSelectDate,string txtStartDate) {
return ("btnValue : " + btnSelectDate + "\ntxtStartDate: " + txtStartDate);
}
}
}
Вид: (.? И для сценариев, я думаю, что есть несколько сценариев, которые дублируются, но я не могу понять тех, что я могу удалить)
@using System;
@using System.Collections.Generic;
@using System.Linq;
@using System.Web;
@using System.Web.Mvc;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" />
<script src="~/Scripts/jquery-1.5.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/scripts/jquery-*.*.*.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>
<script>
$(function() {
$(".Datepicker").datepicker({
dateFormat: "yy-mm-dd",
changeMonth: true,
changeYear: true,
nextText: 'next Month',
prevText: 'previous Month',
showButtonPanel: true,
currentText: 'Today'
})
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSelectDate').click(function (event) {
alert("working");
var text= $('#txtStartDateI').val();
var button= $('#btnSelectDate').val();
$.ajax({
url: "/Home/testtest",
type: "post",
datatype: "text",
data: { btnSelectDate: button, txtStartDate: text},
success: function (data) {
('#testarea').html(data);
},
error: function() {
$('#testarea').html("ERROR");
}
});
});
});
</script>
</head>
<body>
this is test area
<div id="testarea"></div>
<hr />
<p></p>
<div>
<form id="formDTInsurer">
StartDate:
<input type="text" class="Datepicker" id="txtStartDateI" name="txtStartDate">
<button type="submit" id="btnSelectDate" name="btnSelectDate" value="InsurerDate">Select</button>
</form>
</div>
</body>
</html>
Редактировать
После комментария Stephen Muecke «s, я осмотрел консоль с помощью хромированной инструмента. Ниже приведена ошибка.
jquery-1.5.1.js:869
Uncaught TypeError: b.parents(...).addBack is not a function
at Object.parse (jquery.validate.unobtrusive.min.js:19)
at HTMLDocument.<anonymous> (jquery.validate.unobtrusive.min.js:19)
at Object.resolveWith (jquery-1.5.1.js:862)
at Function.ready (jquery-1.5.1.js:420)
at HTMLDocument.DOMContentLoaded (jquery-1.5.1.js:1055)
parse @ jquery.validate.unobtrusive.min.js:19
(anonymous) @ jquery.validate.unobtrusive.min.js:19
resolveWith @ jquery-1.5.1.js:862
ready @ jquery-1.5.1.js:420
DOMContentLoaded @ jquery-1.5.1.js:1055
Поскольку было больше ошибок с этими сценариями, я заметил, некоторые из них, и это на самом деле уменьшается количество ошибок. Единственный слева - тот, что указан выше. Ниже приводится то, что я теперь имею в текущем html-файле.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" />
<!--<script src="~/Scripts/jquery-1.5.1.min.js"></script>-->
<!--<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>-->
<!--<script src="~/scripts/jquery-*.*.*.min.js"></script>-->
<!--<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>-->
Какие ошибки вы получаете в консоли браузера? –
Ошибок нет, но это не работает, как я имел в виду. – pebble
И включите только одну копию скриптов и в правильном порядке - 'jquery- {version} .js', затем' jquery-validate.js' и 'jquery.validate.unobtrusive.js' и' jquery-ui.js' (но это не связано с вашей ошибкой) –