我需要一些帮助。我使用 ASP.NET MVC5 和 JavaScript、jQuery、Ajax 编写了一个小应用程序,但我无法将数据从 javascript 发送到 MVC 控制器并更改模型。
视图模型
public class MyViewModel
{
//...
public string SearchString { get; set; }
public int? FirstInt { get; set; }
public int? SecondInt { get; set; }
}
JavaScript
function keystroke() {
var a = 0, b = 0;
$('#search').keyup(function (event) { a = 1; });
$('#search').keydown(function (event) { b = 1; });
$("#search").keypress(function (event) {
if (e.which === 13) {
e.preventDefault();
$('form').click(function () {
sendForm(a, b);
});
}
});
};
function sendForm(a, b) {
$.ajax({
url: @Url.Action("Index", "Home"),
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
FirstInt: a,
SecondInt: b
}),
success: function () {
alert('success');
}
});
};
View
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form-inline", role = "form" }))
{
<div class="form-group has-feedback">
@Html.TextBox("SearchString", ViewBag.SearchFilter as string, new
{
@class = "form-control",
onclick="keystroke()",
id = "search"
})
</div>
}
控制器
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}
请帮助我将所有值发送到控制器。那些在 JavaScript 中发生更改的内容以及我在文本框中输入的内容。谢谢。