ASP MVC 不验证模型
ASP MVC does not validate model
有一个简单的看法:
@model Bla.SomeModel
<div class="soket-item">
<form>
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Sockets[@index].Count" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
还有一个简单的模型:
public class SomeModel
{
[Required]
[Display(Name = "Charge Count")]
[Range(1, 10)]
public int Count { get; set; }
}
当我设置 Range 属性时,我希望在输入负值时出现警告。但那不会发生。
为什么?
UPD 控制器:
namespace Bla.Controllers
{
[Route("Socket")]
public class MyController : Controller
{
[Route("New")]
public ActionResult NewSocketForm()
{
return View();
}
}
}
这是更新后的代码:
代码 UI
@model SomeModel
<div class="soket-item">
<form asp-controller="Home" asp-action="New" method="post" >
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Count" type="text" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
控制器代码
[HttpPost]
public IActionResult New(SomeModel someModel)
{
if (!ModelState.IsValid)
{
ViewBag.ErrorMessage = "Invalid Input";
}
// do your things
return View("Index");
}
有一个简单的看法:
@model Bla.SomeModel
<div class="soket-item">
<form>
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Sockets[@index].Count" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
还有一个简单的模型:
public class SomeModel
{
[Required]
[Display(Name = "Charge Count")]
[Range(1, 10)]
public int Count { get; set; }
}
当我设置 Range 属性时,我希望在输入负值时出现警告。但那不会发生。 为什么?
UPD 控制器:
namespace Bla.Controllers
{
[Route("Socket")]
public class MyController : Controller
{
[Route("New")]
public ActionResult NewSocketForm()
{
return View();
}
}
}
这是更新后的代码:
代码 UI
@model SomeModel
<div class="soket-item">
<form asp-controller="Home" asp-action="New" method="post" >
<div class="form-group socket-info-group">
<label asp-for="Count" class="control-label"></label>
<input name="Count" type="text" asp-for="Count" class="form-control" />
<span asp-validation-for="Count" class="text-danger"></span>
</div>
<input type="submit" value="Push!" />
</form>
</div>
控制器代码
[HttpPost]
public IActionResult New(SomeModel someModel)
{
if (!ModelState.IsValid)
{
ViewBag.ErrorMessage = "Invalid Input";
}
// do your things
return View("Index");
}