假设我有一个双重类型的属性
[Display(Name = "Retail")]
public double Price { get; set; }
在视图中
@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control",@type="number",@min=0 } })
现在,如果用户没有输入任何内容或删除此textbox中的值.null将在提交时传递给控制器。
无论如何自动为其赋值为0而不向默认情况下双/ int / long数字段的每个字段写入手动javascript?
我的模特
public partial class Product
{
}
public class ProductsAttribute
{
[Display(Name = "Retail")]
[Range(0, double.MaxValue)]
public double Price{ get; set; }
}
数据库首次生成类`
public partial class Product
{
public Product()
{
this.Machines = new HashSet<Machine>();
}
public double Price { get; set; }
public virtual ICollection<Machine> WMFMachines { get; set; }
}
答案 0 :(得分:1)
您可以对服务器端验证使用required
属性和模型验证来控制用户是否在输入中放入空值。您还可以使用客户端验证并在表单提交之前检查输入元素。
我已将NetFiddle作品here添加到服务器和客户端验证
客户端参考:https://www.codeproject.com/Articles/718004/ASP-NET-MVC-Client-Side-Validation
//型号
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
@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>
答案 1 :(得分:0)
在构造函数中设置它
public class ViewModel
{
public ViewModel()
{
this.Price = 0;
}
[Display(Name = "Retail")]
public double Price { get; set; }
}