谷歌显然不是我的朋友,因为我已经尝试了许多发现的建议,但没有一个对我有用。
我有 2 个简单的输入,如下:
<form id="form">
<fieldset id="frmTest">
<div class="form-outline">
@Html.TextBoxFor(m => m.TextBox1, new { @id = "TextBox1", @class = "form-control" })
@Html.LabelFor(m => m.TextBox1, new { @class = "form-label" })
</div>
<div class="form-outline mb-4">
@Html.TextBoxFor(m => m.TextBox2, new { @id = "TextBox2", @class = "form-control" })
@Html.LabelFor(m => m.TextBox2, new { @class = "form-label" })
</div>
</fieldset>
</form>
还有 JS:
$("#SaveTest").click(function (e) {
e.preventDefault();
var data = {
TextBox1: $('#TextBox1').val(),
TextBox2: $('#TextBox2').val(),
};
$.ajax({
type: "POST",
url: "http://localhost/api/api/ConfigurationManagement/TestAjax",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result.message);
},
error: function (response) {
alert(response);
}
});
控制器:
[HttpPost]
public async Task<ActionResult> SaveTest(string TextBox1, string TextBox2)
{
Test model = new Test();
model.TextBox1 = TextBox1;
model.TextBox2 = TextBox2;
_applicationDbContext.Test.Add(model);
try
{
await _applicationDbContext.SaveChangesAsync();
return Ok(new UserManagerResponse { Status = "Success", Message = "Successfully added test" });
}
catch (Exception ex)
{
return BadRequest(new UserManagerResponse { Status = "Failed", Message = ex.ToString() });
}
}
当我单击“SaveTest”按钮时,我看到响应为“错误请求”,指示以下内容,就好像未传递参数一样:
{"errors":{"TextBox1":["The TextBox1 field is required.", "TextBox2":["The TextBox2 field is required."]}
关于奇怪的部分,如果我更改“url”并在末尾添加参数,它就可以工作。
url: "http://localhost/api/api/ConfigurationManagement/TestAjax?textBox1=" + $('#TextBox1').val() + "&TextBox2=" + $('#TextBox2').val(),
虽然这个问题可能看起来是重复的,但我们每个场景都是不同的。我想在不使用 URL 中的参数的情况下执行此操作,我只是不明白为什么在没有 URL 中的参数的情况下它对我不起作用。
谢谢
操作参数默认绑定到查询参数。为了绑定帖子正文中的参数,您需要接受
class
参数,并将 TextBox1
和 TextBox2
作为属性。
public class TxtModel
{
public string TextBox1 { get; set; }
public string TextBox2 { get; set; }
}
[HttpPost]
public async Task<ActionResult> SaveTest(TxtModel model)