gpt4 book ai didi

javascript - 使用ajax将数据从文本框发送到asp.net mvc 5 Controller

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:19 24 4
gpt4 key购买 nike

我需要一些帮助。我使用带有 JavaScript、jQuery、Ajax 的 ASP.NET MVC5 编写小应用程序......我无法将数据从 javascript 发送到 MVC Controller 并更改模型。

View 模型

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');
}
});
};

查看

@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);
}

请帮我把所有的值发送给 Controller 。那些在 JavaScript 中更改的以及我在文本框中输入的内容。谢谢。

最佳答案

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 () {
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 代码

[HttpPost]
public async Task<ActionResult> Index(MyViewModel model)
{
//...
if (model.SearchString != null)
{
//...
var a = model.FirstInt;
var b = model.SecondInt;
}
//...
return View(model);
}

关于javascript - 使用ajax将数据从文本框发送到asp.net mvc 5 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30459261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com