客户端数据注释不适用于部分视图

时间:2012-04-22 03:04:18

标签: asp.net-mvc-3 data-annotations

我在我的asp.net mvc3应用程序中面临一个普遍问题,所有部分视图都不会显示我使用数据注释定义的客户端验证错误,例如我已经定义了以下数据注释: -

public class Country_Validation
    {
        [Required(ErrorMessage="{0} is required.")]
        [StringLength(30, ErrorMessage="{0} is too long.",MinimumLength=1)]
        public string Description { get; set; }
    }

我将使用ajax.beginform调用以下操作方法,然后返回部分视图以创建新的Country对象: -

public ActionResult Create()
        {
            Country c = new Country();
            return PartialView("_Create",c);
        } 

将返回以下_Create部分视图: -

@model Medical.Models.Country

<div id = "partialWrapper">
@using (Ajax.BeginForm("Create", "Country", new AjaxOptions
{
    HttpMethod = "Post",
    InsertionMode = InsertionMode.InsertBefore,
    UpdateTargetId = "Countrytable",
    OnSuccess = "clearform"
}))
{
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Country</legend>
        <div class="editor-label">
        <strong>Country Name:-</strong>
            @Html.EditorFor(model => model.Description)
            @Html.ValidationMessageFor(model => model.Description)
        </div>
            <input type="submit" value="Create" />
    </fieldset>
 }
 </div>

但如果我尝试添加新的country对象,同时将Description字段留空,则不会显示客户端验证错误,而如果我返回常规视图(不是部分)则所有客户端验证错误都能正常工作? 那可能是什么问题呢? BR

1 个答案:

答案 0 :(得分:3)

我最近遇到过类似的事情。解决方案是在我的内容之前(但在我声明我的模型类型和任何using语句之后)将以下内容添加到我的部分视图中:

@{
    ViewContext.FormContext = new FormContext();   
}

您可能还想查看以下链接,该链接涉及为新添加的内容启用验证的javascript方面:

http://xhalent.wordpress.com/2011/01/24/applying-unobtrusive-validation-to-dynamic-content/

相关问题