Reputation: 1704
I need some help. I write little app using ASP.NET MVC5 with JavaScript, jQuery, Ajax... and I can't send data from javascript to MVC Controller and change the model.
ViewModel
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>
}
Controller
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}
Help me, please, to send all the values to controller. Those that changed in JavaScript and what I enter in the textbox. Thanks.
Upvotes: 3
Views: 5660
Reputation: 2134
Javascript Code:
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 () {
var text = $("#search").val()
sendForm(a, b, text);
return false;
});
}
});
};
function sendForm(a, b, text) {
var data = {FirstInt: a,SecondInt: b,SearchString: text}
$.ajax({
url: 'Home/Index',
type: 'POST',
contentType: 'application/json',
data: data,
success: function () {
alert('success');
}
});
};
Controller Code
[HttpPost]
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}
Upvotes: 3