MVC 3 剃刀.部分视图验证不起作用 [英] MVC 3 Razor. Partial View validation is not working

查看:28
本文介绍了MVC 3 剃刀.部分视图验证不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的问题是我无法从我的部分视图中触发客户端验证,在用户单击按钮后加载到 div 中.在此示例中,我已停止 div 的切换"以查看验证是否触发,但无济于事,没有任何反应.

幸运的是,该模型不接受任何无效输入,但它也不会警告用户实际错误.任何帮助将不胜感激.

这是我的模型:

公共类帮助{[HiddenInput(DisplayValue=true)]公共 int HelpID { 获取;放;}[必填(ErrorMessage = "请输入正确的 URL")]公共字符串 URL { 获取;放;}[必填(ErrorMessage = "请输入内容描述:")][数据类型(DataType.MultilineText)]公共字符串 HelpContent { 获取;放;}/*?2个属性可以为空*/公共日期时间?创建日期时间 { 获取;放;}公共日期时间?修改日期时间{获取;放;}}

这是我的控制器:

命名空间 HelpBtn.WebUI.Controllers{/*创建管理控制器*/公共类 AdminController :控制器{//声明接口对象私有 IHelpRepository 存储库;/*将一个数据库接口传递给控制器​​/公共管理控制器(IHelpRepository 存储库){存储库 = 回购;}/*默认管理屏幕.显示帮助表 obs*/公共视图结果索引(){返回视图();}/*返回添加视图表单*/公共 ViewResult AddForm(){返回视图();}/*返回编辑视图表单,用id搜索要编辑的对象如果没有提供 id,默认为 0*/公共 ViewResult EditForm(int helpID = 0){Help help = repository.Help.FirstOrDefault(q => q.HelpID == helpID);返回视图(帮助);}/* 将在用户完成后处理编辑屏幕的帖子提交的编辑信息*/[HttpPost][ValidateInput(false)]//这允许管理员在字段中放置html.可能会导致验证问题public ActionResult EditForm(帮助帮助){if (ModelState.IsValid)//如果所有字段都经过验证{//设置编辑日期help.modifiedDateTime = DateTime.Now;repository.SaveHelp(帮助);return RedirectToAction("索引");}否则//有问题.发回查看{返回视图(帮助);}}/*删除action方法,用id搜索*/[接受动词(HttpVerbs.Post)][网格动作]公共操作结果删除(int helpId){帮助 helpDel = repository.Help.FirstOrDefault(p => p.HelpID == helpId);if (helpDel != null)//如果找到对象,则删除{repository.DeleteHelp(helpDel);}//在所有情况下都返回索引return RedirectToAction("索引");}/*由telerik表用于重新绑定网格*/[网格动作]公共 ActionResult AjaxBinding(){返回视图(新 GridModel(存储库.帮助));}}//结束管理类}//结束命名空间

这是我的主视图:

<div id="addContent" style="display: none"></div>//选择函数.保存选定行函数 onRowSelect(e) {HelpID = e.row.cells[0].innerHTML;}//结束onRowSelect//刷新网格函数函数 refreshGrid() {$("#Grid").data('tGrid').rebind();}//结束刷新网格//变量.'$' b4 智能感知名称无功帮助ID;var $editContent = $("#editContent");var $addContent = $("#addContent");//结束变量//添加表单调用.将部分视图加载到 div:content$("#Add").click(function () {$editContent.hide();$editContent.html("");$.ajax({类型:获取",url: "/Admin/AddForm",数据类型:html",成功:功能(数据){$addContent.html(data);$addContent.toggle();}//结束成功});//结束ajax});//结束添加//编辑表单调用.将部分视图加载到 div:content$("#Edit").click(function () {$addContent.hide();$addContent.html("");$.ajax({类型:获取",url: "/Admin/EditForm",数据类型:html",数据:{帮助ID:帮助ID},成功:功能(数据){$editContent.html(data);$editContent.toggle();}//结束成功});//结束ajax});//结束编辑//删除调用.删除表中选定的行$("#Delete").live('click', function () {$.post("/Admin/Delete", { HelpID: HelpID }, function () {$addContent.html("");$editContent.html("");刷新网格();});//结束函数});//结束删除//将表单数据发送回服务器$("#btnAdd").live('click', function (e) {e.preventDefault();$.post($('#Addx').attr('action'), $('#Addx').serialize(), 函数(数据){刷新网格();$addContent.html("");});//结束帖子e.preventDefault();});//结束 .live//将编辑的表单数据发布回服务器$("#btnEdit").live('click', function (e) {$.post($('#Editx').attr('action'), $('#Editx').serialize(), 函数(数据){刷新网格();$editContent.html("");});e.preventDefault();});//结束帖子编辑

这是我的部分视图,加载到主页的 div 中:

@model HelpBtn.Domain.Entities.Help@*此帖子返回编辑/管理员.需要异步*@@using (Html.BeginForm("EditForm", "Admin", FormMethod.Post, new { id = "Addx" })){<字段集><legend>添加条目</legend><div class="editor-label">@Html.LabelFor(model => model.URL)

<div class="editor-field">@Html.EditorFor(model => model.URL)@Html.ValidationMessageFor(model => model.URL)

<div class="editor-label">@Html.LabelFor(model => model.HelpContent, "帮助内容")

<div class="editor-field">@Html.EditorFor(model => model.HelpContent)<p>@Html.ValidationMessageFor(model => model.HelpContent, "输入一个值")</p>

<div class="editor-label">@Html.LabelFor(model => model.createDateTime, "创建日期")

<div class="editor-field">@Html.EditorFor(model =>model.createDateTime)@Html.ValidationMessageFor(model =>model.createDateTime)

<p><input id="btnAdd" type="submit" value="Create"/></p></fieldset>}

解决方案

每次执行 AJAX 调用并用控制器操作返回的部分 HTML 内容替换部分 DOM 时,您都需要重新解析客户端不显眼的验证规则.所以在你的 AJAX 成功回调中,当你调用 .html() 方法刷新你需要解析的 DOM 之后:

$('form').removeData('validator');$('form').removeData('unobtrusiveValidation');$.validator.unobtrusive.parse('form');

I'm having the problem that I cannot get client-side validation to fire from within my partial view, that loads into a div after a user clicks a button. In this example I've stopped the div from "toggling" to see if the validation fires, but to no avail, nothing happens.

Luckily, the model doesn't accept any invalid input, but it also doesn't warn the user of the actual mistake. Any help would be appreciated.

Here is my Model:

public class Help
{
    [HiddenInput(DisplayValue=true)]
    public int HelpID { get; set; }

    [Required(ErrorMessage = "Please enter a proper URL")]
    public string URL { get; set; }

    [Required(ErrorMessage = "Please enter a content description:")]
    [DataType(DataType.MultilineText)]
    public string HelpContent { get; set; }

    /*? 2 properites are nullable*/
    public DateTime? createDateTime { get; set; }
    public DateTime? modifiedDateTime { get; set; }        
}

Here is my Controller:

namespace HelpBtn.WebUI.Controllers
{
    /*Create the admin controller*/
    public class AdminController : Controller
    {
        //declare interface object
        private IHelpRepository repository;

        /*Pass a db interface to controller*/
        public AdminController(IHelpRepository repo)
        {
            repository = repo;
        }

        /*default admin screen. displays help table obs*/
        public ViewResult Index()
        {
            return View();
        }

        /*Returns add view form*/
        public ViewResult AddForm()
        {
            return View();
        }

        /*Returns edit view form, searches for object to edit with id
          if no id provided, 0 by default*/
        public ViewResult EditForm(int helpID = 0)
        {
            Help help = repository.Help.FirstOrDefault(q => q.HelpID == helpID);
            return View(help);
        }

        /*Will handle the post for the edit screen after user has
          submitted edit information*/
        [HttpPost]
        [ValidateInput(false)] //this allows admin to place html in field. may cause validation problems
        public ActionResult EditForm(Help help)
        {

            if (ModelState.IsValid) //if all fields are validated
            {
                //set the edit date
                help.modifiedDateTime = DateTime.Now;
                repository.SaveHelp(help);
                return RedirectToAction("Index");
            }
            else //there is something wrong. send back to view            
            {
                return View(help);
            }
        }

        /*Delete action method, searches with id*/
        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult Delete(int helpId)
        {
            Help helpDel = repository.Help.FirstOrDefault(p => p.HelpID == helpId);
            if (helpDel != null) //if the object is found, delete
            {
                repository.DeleteHelp(helpDel);
            }

            //in all cases return to index
            return RedirectToAction("Index");
        }

        /*Used by the telerik table to rebind grid*/
        [GridAction]
        public ActionResult AjaxBinding()
        {
            return View(new GridModel(repository.Help));
        }
    }//end admin class
}//end namespace

Here is my Main View:

<div id="addContent" style="display: none"></div>

//Select Function. saves selected row
function onRowSelect(e) {
    HelpID = e.row.cells[0].innerHTML;
} //end onRowSelect

//Refresh grid function
function refreshGrid() {
    $("#Grid").data('tGrid').rebind();
} //end refresh grid

//Variables. '$' b4 name for intellisense
var HelpID;
var $editContent = $("#editContent");
var $addContent = $("#addContent");
//end variables  

//Add Form call. loads partial view to div:content
$("#Add").click(function () {
    $editContent.hide();
    $editContent.html("");
    $.ajax({
        type: "Get",
        url: "/Admin/AddForm",
        datatype: "html",
        success: function (data) {
            $addContent.html(data);
            $addContent.toggle();
        } //end success
    }); //end ajax
});        //end add

//Edit Form call. loads partial view to div:content
$("#Edit").click(function () {
    $addContent.hide();
    $addContent.html("");
    $.ajax({
        type: "Get",
        url: "/Admin/EditForm",
        dataType: "html",
        data: { HelpID: HelpID },
        success: function (data) {
            $editContent.html(data);
            $editContent.toggle();
        } //end sucess
    }); //end ajax
});         //end edit

//Delete call. deletes selected row in table
$("#Delete").live('click', function () {
    $.post("/Admin/Delete", { HelpID: HelpID }, function () {
        $addContent.html("");
        $editContent.html("");
        refreshGrid();
    }); //end function
});   //end delete

//post add form data back to server
        $("#btnAdd").live('click', function (e) {
            e.preventDefault();
            $.post($('#Addx').attr('action'), $('#Addx').serialize(), function (data) {
                refreshGrid();
             $addContent.html("");
            }); //end post
            e.preventDefault();
        });
        //    end .live

        //post edit form data back to server
        $("#btnEdit").live('click', function (e) {
            $.post($('#Editx').attr('action'), $('#Editx').serialize(), function (data) {
                refreshGrid();
                $editContent.html("");
            });

            e.preventDefault();
        }); //end post edit

And here is my partial view, that loads into the main page's div:

@model HelpBtn.Domain.Entities.Help
@*THIS POSTS BACK TO EDIT/ADMIN. needs to be asynchronous*@
@using (Html.BeginForm("EditForm", "Admin", FormMethod.Post, new { id = "Addx" }))
{
    <fieldset>
        <legend>Add Entry</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.URL)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.URL)
            @Html.ValidationMessageFor(model => model.URL)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.HelpContent, "Help Content")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.HelpContent)
            <p>
                @Html.ValidationMessageFor(model => model.HelpContent, "Enter a value")
            </p>
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.createDateTime, "Created Date")
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.createDateTime)
            @Html.ValidationMessageFor(model => model.createDateTime)
        </div>
        <p>
            <input id="btnAdd" type="submit" value="Create" />
        </p>
    </fieldset>   
}

解决方案

Everytime you perform an AJAX call and substitute some part of your DOM with partial HTML contents returned by the controller action you need to reparse the client side unobtrusive validation rules. So in your AJAX success callbacks when after you call the .html() method to refresh the DOM you need to parse:

$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');

这篇关于MVC 3 剃刀.部分视图验证不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆