【发布时间】:2020-06-07 16:37:17
【问题描述】:
有时我完全不明白。我只想创建一个表单,用户可以在其中输入一个字段,必须选中一个复选框,并且只有在选中该复选框时,提交按钮才有效。 所以我的模型看起来像这样:
[Table("ResetType")]
public class ResetTypeModel
{
public bool IsTrue => true;
[Display(Name = "Hostname")]
[Required]
[StringLength(11, MinimumLength=11)]
[RegularExpression("^[a-zA-Z]{2}[a-zA-Z]{1}[a-zA-Z0-9]{2}[0-9]{3}[a-zA-Z]{3}$")]
public string hostname {get; set;}
[Required]
[RegularExpression("(True|true)")]
[Display(Name = "I agree to the terms and conditions")]
[Compare(nameof(IsTrue), ErrorMessage = "Please agree to Terms and Conditions")]
public bool confirmed {get; set;}
}
}
我的控制器调用视图:
public IActionResult Reset()
{
return View();
}
最后是我目前的观点:
@using (Html.BeginForm("ResetDevice", "Test", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="media-body">
<label for="resettype_name">Reset Type</label>
<select class="form-control" data-val="true" id="ddl_resettype" ><option value="">Please select a Reset Type</option>
<option value="Delete">Delete</option>
<option value="Reset">Reset</option>
</select>
</div>
<div class="media-body" >
<label for="label_hostname">Hostname</label>
<input class="form-control" name="hostname" id="hostname" />
@Html.LabelFor(model=> model.hostname)
@Html.TextBoxFor(m => m.hostname, new { @class = "form-control" })
@* <input asp-for="model.hostname" class="form-control" name="hostname" id="hostname" /> *@
@* <input type="checkbox" id="Authorized" name="Authorized" /> *@
@Html.CheckBoxFor(x => x.confirmed)
@Html.LabelFor(m => m.confirmed)
@Html.EditorFor(model => model.confirmed)
@Html.ValidationMessageFor(m => m.confirmed)
</div>
<input type="submit" value="Reset" class="btn btn-primary" />
}
@section Scripts
{
<script src="~/js/jquery-3.5.1.min.js" defer></script>
<script src="~/js/jquery.validate.js" defer></script>
当我单击提交按钮时,没有任何验证,但我想我在过去几天有过一次,在一段时间内有另一个视图,其次,更重要的是,我在 POST 到控制器
[HttpPost]
//[Route("ResetDevice")]
[ValidateAntiForgeryToken]
public IActionResult ResetDevice([FromBody] ResetTypeModel rtm){
return RedirectToAction("Reset", "Test");
}
好像方法没有被调用。
我错过了什么?
更新:
当我将它称为 ajax 时,它正在工作,那么我错过了什么?
$.ajax({
type: "POST",
url: 'ResetDevice',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
traditional: true,
success: function () {
alert("Successfully Imported");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR:" + jqXHR.status + " errorThrown: " + errorThrown);
}
更新:
好的,我想我发现了错误。在控制器中,我使用 FromBody 而不是 FromForm
【问题讨论】:
-
不要使用 IActionResult ,而是尝试在 GET 和 POST 方法中使用 ActionResult
标签: asp.net asp.net-core