Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 两个属性asp.net mvc之间条件的数据验证属性_C#_Asp.net_Asp.net Mvc - Fatal编程技术网

C# 两个属性asp.net mvc之间条件的数据验证属性

C# 两个属性asp.net mvc之间条件的数据验证属性,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我想在两个属性之间设置一个规则,即一个属性必须大于另一个属性。 那么,什么是数据验证属性,可以让我这样做 这是我的财产 public int Min{get;set;} public int Max{get;set;} 正如您可以很容易理解的那样,Max必须大于Min 谢谢你的帮助 使用Jquery可以轻松实现所需的功能,如图所示:- HTML:- <input type="text" id="Max" name="Max" /> //with model valid

我想在两个属性之间设置一个规则,即一个属性必须大于另一个属性。 那么,什么是数据验证属性,可以让我这样做

这是我的财产

  public int Min{get;set;}
  public int Max{get;set;} 
正如您可以很容易理解的那样,Max必须大于Min


谢谢你的帮助

使用Jquery可以轻松实现所需的功能,如图所示:-

HTML:-

<input type="text" id="Max" name="Max"  />  //with model validations just make sure user can input numbers in Max and Min textboxes.
<input type="text" id="Min" name="Min" />
<div id="errormess"></div>
//通过模型验证,只需确保用户可以在Max和Min文本框中输入数字即可。
Jquery:

$(document).ready(function(){
   $("#Max").focusout(function(){
      if(parseInt($(this).val()) < parseInt($("#Min").val()))
      {
         $("#errormess").html('Max value cannot be lower then Min Value');
      }
      else{ $("#errormess").html(''); }
   });

   $("#Min").focusout(function(){
      if(parseInt($(this).val()) > parseInt($("#Max").val()))
      {
         $("#errormess").html('Max value cannot be lower then Min Value');
      }
      else{ $("#errormess").html(''); }
   });
});
$(文档).ready(函数(){
$(“#Max”).focusout(函数(){
if(parseInt($(this.val())parseInt($(“#Max”).val())
{
$(“#errormess”).html('最大值不能低于最小值');
}
else{$(“#errormess”).html(“”)}
});
});

我同意一个例外,JQuery比模型本身更容易实现这种功能。然而,尽管没有Javascript/Jquery方面的经验,但值得一看Jquery的文档

你还可以找到很棒的教程

最重要的部分是实际的JQuery库文件。您可以下载该文件并将其包含在解决方案中,或者只需在视图的标题中包含指向该文件的服务器托管CDN版本的链接。(两个选项都在我给你的链接上提供了说明)

但是,您不包括在输入控件中仅允许整数值所需的功能。要解决这个问题,只需将inputs type属性更改为“number”,如下所示

<input type="number" id="Max" name="Max"  />

并修改脚本以删除字符串到整数的解析,如下所示:

$("#Max").focusout(function(){
      if( $(this).val() < $("#Min").val() )
      {
         $("#errormess").html('Max value cannot be lower then min Value');
      }
      else{ $("#errormess").html(''); }
   });

   $("#Min").focusout(function(){
      if( $(this).val() >= $("#Max").val() )
      {
         $("#errormess").html('Max value cannot be lower then min Value');
      }
      else{ $("#errormess").html(''); }
   });
$(“#Max”).focusout(函数(){
if($(this.val()<$(“#Min”).val())
{
$(“#errormess”).html('最大值不能低于最小值');
}
else{$(“#errormess”).html(“”)}
});
$(“#Min”).focusout(函数(){
if($(this.val()>=$(“#Max”).val())
{
$(“#errormess”).html('最大值不能低于最小值');
}
else{$(“#errormess”).html(“”)}
});

我觉得对对象进行数据验证是件好事(以及使用客户端验证)

这是一个属性,您可以使用它来执行您所要求的操作(它将能够比较实现IComparable的类型对)


这是一个关于小于验证的有用问题,但适用于日期而不是整数,但同样的方法适用于

您可以使用属性,或者您的视图模型可以实现IValidatableObject。很好的是asp.net mvc modelbinder将在post上自动运行此功能

public class TestCompareModel : IValidatableObject
{
    [Required]
    public Int32 Low { get; set; }

    [Required]
    public Int32 High { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        if (High < Low)
            results.Add(new ValidationResult("High cannot be less than low"));

        return results;
    }
}
看法

@model Scratch.Web.Models.TestCompareModel
@{
ViewBag.Title=“测试”;
}
试验
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
测试比较模型

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.Low,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Low,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Low,“,new{@class=“text danger”}) @LabelFor(model=>model.High,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.High,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.High,“,new{@class=“text danger”}) } @ActionLink(“返回列表”、“索引”)
使用jquery而不是模型验证我更喜欢模型验证我不知道如何处理JqueryOkk..但据我所知,mvc很难获得您的功能,唯一的方法是将其设置为自定义验证属性,但使用jquery非常简单..好的,您能告诉我如何实现吗?这些最小值和最大值是文本框???I我个人喜欢这种方法。即使现在,每个人都可能启用了javascript,但在客户端和服务器上执行验证仍然是最佳实践。如果你只在一个地方做,我还是会在服务器端做。您可能应该这样做,下面的JQuery解决方案就是这个答案。谢谢!!您的帖子非常有趣最佳实践提示:[GreaterThan(nameof(Min))]如果您想获得更高的评价,请将1替换为0。非常感谢您的帮助!!谢谢你的帮助,现在更清楚了!这应该被标记为答案!它符合DRY,并在客户端生成验证代码。我可以要求一个帖子,因为这种验证更多的是业务/领域验证。还要编写的代码也少得多(没有新的属性类或向视图添加逻辑)。
  public int Min{get;set;}

  [GreaterThan("Min")]
  public int Max{get;set;}
public class TestCompareModel : IValidatableObject
{
    [Required]
    public Int32 Low { get; set; }

    [Required]
    public Int32 High { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();

        if (High < Low)
            results.Add(new ValidationResult("High cannot be less than low"));

        return results;
    }
}
    [HttpPost]
    public ActionResult Test(TestCompareModel viewModel)
    {
        if (!ModelState.IsValid)
            return View(viewModel);

        return RedirectToAction("Index");
    }
@model Scratch.Web.Models.TestCompareModel

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>TestCompareModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Low, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Low, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Low, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.High, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.High, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.High, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>