如何在没有模型的情况下验证MVC3中的强类型视图

时间:2012-04-19 23:45:09

标签: jquery asp.net-mvc-3 validation

我对项目感到困惑。 该项目有3层:

  1. 使用ado.net数据模型进行数据访问。
  2. 从de数据访问ado.net数据中检索数据的WCF服务 模型并发送序列化的类。
  3. 连接到wcf服务的MVC Web应用程序。
  4. wcf服务的类包含从其他层(数据访问层)检索数据并返回mvc应用程序的程序(这没​​有问题) 我已经创建了一个强大的类型视图(来自wcf服务参考),它显示了产品类别并且很好地购买我不知道如何验证这个视图!

    我见过很多关于验证的文章,其中大部分是使用模型和数据注释但不是我的情况。我发现了一些关于jquery验证的文章,但我已经尝试过没有任何反应......这里是视图的代码:

    @model SkySolutionsMVC3.ProductCategoryServiceReference.CompositeProductCategory
    @{
        ViewBag.Title = "Edit";
    }
    <h2>
        Edit</h2>
    <script src="@Url.Content("~/Scripts/jquery-1.7.2.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
    
    
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Product Category</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.Enabled)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Enabled)
                @Html.ValidationMessageFor(model => model.Enabled)
            </div>
            @Html.HiddenFor(model => model.Id)
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name, new { id="Name"})
                @Html.ValidationMessageFor(model => model.Name)
            </div>
            <p>
                <input type="submit" name="btnSave" value="Save" />
            </p>
        </fieldset>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    

    请帮忙!我需要一些想法......谢谢。

1 个答案:

答案 0 :(得分:0)

我不完全确定你是在追求它,但如果你说你基本上需要控制从其他地方导入的类,那么怎么样:编写你自己的类,继承你正在使用的类现在作为模型并从IValidatableObject继承, 然后为重写的属性添加适当的注释或实现Validate方法,如下所示:


public class MyClass : SkySolutionsMVC3.ProductCategoryServiceReference.CompositeProductCategory, IValidatableObject
{
    [Required]
    public override string Name
    {
        get { return base.Name; }
        set { base.Name = value; }
    }

    public IEnumerable Validate(ValidationContext validationContext)
    {
        if (Name.Length != 5)
        {
            yield return new ValidationResult("Name must be exaclty 5 characters long", new string[]{"Name"});
        }
    }
}