验证错误在asp.net mvc中不可见partialView

时间:2012-10-15 21:08:31

标签: asp.net-mvc asp.net-mvc-4

我有一个DropDownList控件和文本框的部分视图。

如果未选择任何内容或未输入任何文本,则ModelState.IsValid为FALSE

但是我可以看到没有在我的属性上显示注释的验证错误。

为什么?我可以在ModelState.Value.Errors属性中看到有一个"名称是

缺失"例如。

当我确认无效视图时,我在输出窗口中看到了这一点:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll
A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll


public ActionResult Edit()
{
    return LoadEditTemplates();
}


[HttpPost]
public ActionResult Update(EditTemplateListViewModel viewModel)
{
    if (ModelState.IsValid && !_templateDataProvider.TemplateExists(viewModel.Name))
    {
        Template template = Mapper.Map<EditTemplateListViewModel, Template>(viewModel);
        _templateDataProvider.UpdateTemplate(template);
        return new JsonNetResult(new { success = true });
    }

    return PartialView(viewModel);
}

private ActionResult LoadEditTemplates()
{
    var templates = _templateDataProvider.GetTemplates();
    EditTemplateListViewModel editTemplateViewModel = new EditTemplateListViewModel()
    {
        DisplayList = Mapper.Map<IEnumerable<Template>, IEnumerable<TemplateViewModel>>(templates),
    };
    return PartialView(editTemplateViewModel);
}

public class EditTemplateListViewModel
    {
        [Required(ErrorMessage = "No template selected.")]
        public int TemplateId { get; set; }

        [Required(ErrorMessage="Name is missing")]
        public string Name { get; set; }

        public IEnumerable<TemplateViewModel> DisplayList { get; set; }      
    }

@model ITMS.Web.Models.EditTemplateListViewModel

@*Remote Validation*@
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm("Update", "Template"))
{       
    @Html.ValidationSummary(false)
    @Html.DropDownListFor(x => x.TemplateId, new SelectList(Model.DisplayList, "TemplateId", "Name"), new { @class = "listviewmodel" })

    <p class="editor-label">@Html.LabelFor(model => model.Name)</p>
    <p class="editor-field">@Html.EditorFor(model => model.Name)</p>
    <p class="editor-field">@Html.ValidationMessageFor(model => model.Name)</p>   
}

3 个答案:

答案 0 :(得分:1)

Insated使用Html,BeginForm使用Ajax.BeginForm提交您的局部视图

   //In partial View 


<div id="targetId">
     @using (Ajax.BeginForm("Update", "Template", new AjaxOptions { HttpMethod="POST", UpdateTargetId="targetId"}))
        {       
            @Html.ValidationSummary(false)
            @Html.DropDownListFor(x => x.TemplateId, new SelectList(Model.DisplayList, "TemplateId", "Name"), new { @class = "listviewmodel" })

            <p class="editor-label">@Html.LabelFor(model => model.Name)</p>
            <p class="editor-field">@Html.EditorFor(model => model.Name)</p>
            <p class="editor-field">@Html.ValidationMessageFor(model => model.Name)</p>   
        }

部分视图的返回类型是字符串所以你可以在服务器端捕获它,在ajax选项中你必须指定HttpMethod和UpdateTargetId你想在视图中显示你的结果。我引用了你的Ajax.BegionForm与div和给定的UpdateTargetId是Div Id,这样如果发生错误,它会在同一个div中附加视图

在控制器

[HttpPost]
public string Update(EditTemplateListViewModel viewModel)
{
    if (ModelState.IsValid && !_templateDataProvider.TemplateExists(viewModel.Name))
    {
        Template template = Mapper.Map<EditTemplateListViewModel, Template>(viewModel);
        _templateDataProvider.UpdateTemplate(template);
        return new JsonNetResult(new { success = true });
    }

    return RenderPartialViewToString("PartialViewName",viewModel);
}



protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

通过将partialViewName和Model传递给RenderPartialViewToStringit,将返回View的 RenderHtml

注意:在使用Ajax.BeginForm之前,请确保添加以下脚本。

答案 1 :(得分:1)

当我从post动作返回数据时,我意识到Argument强制转换异常,因为我没有将数据传递给SelectItem列表“DisplayList”。它是空的,因此爆炸......

我只是填写了缺失的数据来重新显示视图,错误是可见的:)哎呀......我已经介入了一次失败......

答案 2 :(得分:0)

由于服务器端代码工作正常,我建议检查是否正确加载了所需的JQuery库。

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.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>