Javascript 服务器端和客户端双输入字段的模型验证
假设我有一个双重类型的属性Javascript 服务器端和客户端双输入字段的模型验证,javascript,c#,asp.net-mvc,Javascript,C#,Asp.net Mvc,假设我有一个双重类型的属性 [Display(Name = "Retail")] public double Price { get; set; } 鉴于 @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control",@type="number",@min=0 } }) 现在,如果用户没有输入任何内容或删除此文本框中的值,则提交时将传递给控制器 默认情况下,是否自动为
[Display(Name = "Retail")]
public double Price { get; set; }
鉴于
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control",@type="number",@min=0 } })
现在,如果用户没有输入任何内容或删除此文本框中的值,则提交时将传递给控制器
默认情况下,是否自动为其赋值0,而不向double/int/long number字段的每个字段写入手动javascript
我的型号
public partial class Product
{
}
public class ProductsAttribute
{
[Display(Name = "Retail")]
[Range(0, double.MaxValue)]
public double Price{ get; set; }
}
@using (Html.BeginForm()) {
.......
}
@section Scripts
{
Scripts.Render("~/bundles/jqueryval")
}
数据库第一个生成的类`
public partial class Product
{
public Product()
{
this.Machines = new HashSet<Machine>();
}
public double Price { get; set; }
public virtual ICollection<Machine> WMFMachines { get; set; }
}
公共部分类乘积
{
公共产品()
{
this.Machines=newhashset();
}
公共双价{get;set;}
公共虚拟ICollection WMFMachines{get;set;}
}
您可以使用服务器端验证的属性和模型验证来控制用户是否在输入中输入空值。您还可以使用客户端验证,并在提交表单之前检查输入元素
我添加了NetFiddle works与服务器端和客户端验证
客户端参考:
//型号
public class YourModel
{
[Required(ErrorMessage = "Price is required")]
[Display(Name = "Retail")]
[Range(0, double.MaxValue)]
public double Price { get; set; }
}
//控制器
[HttpGet]
public ActionResult Index()
{
return View(new YourModel());
}
[HttpPost]
public ActionResult Index( YourModel model)
{
if(ModelState.IsValid)
{
//model is valid, add your code here
}
else
{
//returns with model validation error
return View();
}
}
//html
public partial class Product
{
}
public class ProductsAttribute
{
[Display(Name = "Retail")]
[Range(0, double.MaxValue)]
public double Price{ get; set; }
}
@using (Html.BeginForm()) {
.......
}
@section Scripts
{
Scripts.Render("~/bundles/jqueryval")
}
//web.config
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
</configuration>
在构造函数中设置它
public class ViewModel
{
public ViewModel()
{
this.Price = 0;
}
[Display(Name = "Retail")]
public double Price { get; set; }
}
您不能在模型的构造函数中设置默认值吗?在控制器的参数中写入=0
可以做到这一点,对吗?有一个技巧可以使列的属性为null。如果用户没有输入任何值,它将保存空值,如果我在3页中使用它。我在控制器中需要3次?如果我的实体有3次以上。意味着我需要在3页中分配9次。在构造函数中:用户按backspace,值将消失。提交时。它仍将为null。该属性不可为null
,因此将在POST方法中将其初始化为零。Ad如果您已实施客户端验证,则除非输入具有有效数字,否则您甚至无法提交。如果用户手动按下后间距并删除值并提交,该怎么办?您可以向字段添加所需数据。annatotaions以使用model.state.isValidt验证您的字段属性为double
。它已经初始化为零。构造函数是没有意义的@用户也正确。我一直认为零是不必要的。因为零也是一个值,所以我也应该设置为必需的,属性是double
。它已经初始化为零。构造函数是没有意义的!