【问题标题】:Model validation for double input field in server and client side服务器端和客户端双输入字段的模型验证
【发布时间】:2017-06-22 08:11:10
【问题描述】:

假设我有一个双重类型的属性

[Display(Name = "Retail")]
public double Price { get; set; }

在视图中

@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control",@type="number",@min=0 } })

就目前而言,如果用户没有输入任何内容或删除此文本框中的值。null 将在提交时传递给控制器​​。

默认情况下自动为其分配 0 的值,而无需为 double/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; }
}

【问题讨论】:

  • 不能在model的构造函数中设置默认值吗?
  • 在控制器的参数中写入=0 可以解决问题,对吧?
  • 一个技巧可以让列的属性为空。如果用户不输入任何值,它将保存空值
  • 如果我在 3 页中使用它。我需要在控制器中 3 次?如果我的实体有超过 3 个。意味着我需要在 3 页中分配它 9 次。在构造函数中:用户按退格键,该值将消失。提交时。它仍然是空的。
  • 属性不是nullable,所以会在POST方法中初始化为零。如果你已经实现了客户端验证,你甚至不能提交,除非输入有一个有效的数字。

标签: javascript c# asp.net-mvc


【解决方案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>

【讨论】:

  • 如果用户手痒按回间距去掉值再提交怎么办?
  • 您可以将所需的 data.annatotaions 添加到字段以使用 model.state.IsValid 验证您的字段
  • 属性为double。它已经初始化为零。构造函数毫无意义!
  • @user 也是如此。我一直有这种不需要零的心态。因为零是一个值,所以我也应该设置为 required
【解决方案2】:

在构造函数中设置

public class ViewModel
{
   public ViewModel()
   { 
       this.Price = 0;
   }

   [Display(Name = "Retail")]
   public double Price { get; set; }    
}

【讨论】:

  • 属性是double。它已经初始化为零。构造函数毫无意义!
猜你喜欢
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 2012-02-05
  • 2011-10-17
相关资源
最近更新 更多