MVC 3剃须刀。局部视图验证不工作 [英] MVC 3 Razor. Partial View validation is not working

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

问题描述

我有,我不能让客户端验证从我的局部视图内火,加载到用户后,一个div点击一个按钮的问题。在这个例子中,我停止了从反复的div来看看验证火灾,但都无济于事,什么都不会发生。

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

这里是我的模型:

 公共类帮助
{
    [HiddenInput(DisplayValue =真)]
    公众诠释的helpID {搞定;组; }    [必需(的ErrorMessage =请输入正确的网址)]
    公共字符串URL {搞定;组; }    [必需(的ErrorMessage =请输入内容描述:)]
    [数据类型(DataType.MultilineText)
    公共字符串HelpContent {搞定;组; }    / *? 2型属性可为空* /
    公众的DateTime? createDateTime {搞定;组; }
    公众的DateTime? modifiedDateTime {搞定;组; }
}

这是我的控制器:

 命名空间HelpBtn.WebUI.Controllers
{
    / *创建管理员控制* /
    公共类AdminController:控制器
    {
        //声明接口对象
        私人IHel prepository库;        / *传递一个DB接口控制器* /
        公共AdminController(IHel prepository回购)
        {
            库=回购;
        }        / *默认的管理员屏幕。显示帮助台OBS * /
        公众的ViewResult指数()
        {
            返回查看();
        }        / *回报添加视图形式* /
        公众的ViewResult AddForm()
        {
            返回查看();
        }        / *返回编辑视图的形式,将搜索对象ID为编辑
          如果没有ID提供的,缺省值为0 * /
        公众的ViewResult EditForm(INT的helpID = 0)
        {
            帮助帮助= repository.Help.FirstOrDefault(Q => q.HelpID ==的helpID);
            返回查看(帮助);
        }        / *将处理后的编辑屏幕用户后,
          提交编辑信息* /
        [HttpPost]
        [ValidateInput(假)] //这允许管理员放置在HTML领域。可能会导致验证问题
        公众的ActionResult EditForm(帮助帮助)
        {            如果(ModelState.IsValid)//如果所有的字段都验证
            {
                //设置编辑日期
                help.modifiedDateTime = DateTime.Now;
                repository.SaveHelp(帮助);
                返回RedirectToAction(「指数」);
            }
            否则//有什么不对。发送回浏览
            {
                返回查看(帮助);
            }
        }        / *删除的操作方法,用ID搜索* /
        的[AcceptVerbs(HttpVerbs.Post)
        [GridAction]
        公众的ActionResult删除(INT的helpID)
        {
            帮助helpDel = repository.Help.FirstOrDefault(P => p.HelpID ==的helpID);
            如果(helpDel!= NULL)//如果找到对象,删除
            {
                repository.DeleteHelp(helpDel);
            }            //在所有情况下返回索引
            返回RedirectToAction(「指数」);
        }        / *由Telerik的表用于重新绑定网格* /
        [GridAction]
        公众的ActionResult AjaxBinding()
        {
            返回查看(新GridModel(repository.Help));
        }
    } //结束管理类
} //结束空间

这是我的主要观点:

 < D​​IV ID =addContent的风格=显示:无>< / DIV>//选择功能。节省选定的行
功能onRowSelect(五){
    的helpID = e.row.cells [0] .innerHTML;
} //结束onRowSelect//刷新网格功能
功能refreshGrid(){
    $(#网格)的数据(tGrid')重新绑定()。
} //结束刷新网格//变量。 $智能感知B4名
VAR的helpID;
变量$ editContent = $(#editContent);
变量$ addContent = $(#addContent);
//结束变量//添加窗体调用。负载部分以DIV:内容
$(#添加)。点击(函数(){
    $ editContent.hide();
    $ editContent.html();
    $阿贾克斯({
        键入:获取,
        网址:/管理/ AddForm
        数据类型:HTML,
        成功:功能(数据){
            $ addContent.html(数据);
            $ addContent.toggle();
        } //成功结束
    }); //结束阿贾克斯
}); //最后添加//编辑表单电话。负载部分以DIV:内容
$(#编辑)。点击(函数(){
    $ addContent.hide();
    $ addContent.html();
    $阿贾克斯({
        键入:获取,
        网址:/管理/ EditForm
        数据类型:HTML,
        数据:{的helpID:}的helpID,
        成功:功能(数据){
            $ editContent.html(数据);
            $ editContent.toggle();
        } //结束sucess
    }); //结束阿贾克斯
}); //结束编辑//删除呼叫。删除表中选择行
$(#删除)。生活('点击',功能(){
    $。员额(/管理/删除,{的helpID:}的helpID,函数(){
        $ addContent.html();
        $ editContent.html();
        refreshGrid();
    }); //函数结束
}); //删除结束//添加后表单数据发送回服务器
        $(#btnAdd)。生活('点击',功能(E){
            亦即preventDefault();
            $。员额($('#ADDX')。ATTR(行动),$('#ADDX')。序列化(),功能(数据){
                refreshGrid();
             $ addContent.html();
            }); //结束后
            亦即preventDefault();
        });
        //结束.live        //后编辑表单数据传回服务器
        $(#btnEdit)。生活('点击',功能(E){
            $。员额($('#Editx')。ATTR(行动),$('#Editx')。序列化(),功能(数据){
                refreshGrid();
                $ editContent.html();
            });            亦即preventDefault();
        }); //结束后编辑

这是我的部分观点,即加载到主网页的DIV:

  @model HelpBtn.Domain.Entities.Help
@ *本帖子返回编辑/ ADMIN。需要异步* @
@using(Html.BeginForm(EditForm,管理,FormMethod.Post,新{ID =ADDX}))
{
    <&字段集GT;
        <传奇>添加条目< /传说>
        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.URL)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.URL)
            @ Html.ValidationMessageFor(型号=> model.URL)
        < / DIV>
        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.HelpContent,帮助内容)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.HelpContent)
            &所述p为H.;
                @ Html.ValidationMessageFor(型号=> model.HelpContent,输入一个值)
            &所述; / P>
        < / DIV>
        < D​​IV CLASS =编辑标记>
            @ Html.LabelFor(型号=> model.createDateTime,创建日期)
        < / DIV>
        < D​​IV CLASS =主编场>
            @ Html.EditorFor(型号=> model.createDateTime)
            @ Html.ValidationMessageFor(型号=> model.createDateTime)
        < / DIV>
        &所述p为H.;
            <输入ID =btnAdd类型=提交值=创建/>
        &所述; / P>
    < /字段集>
}


解决方案

每当你执行一个AJAX调用,并以由你需要重新解析客户端不显眼的验证规则控制器动作返回部分HTML内容的DOM的某些部分。因此,在您成功的AJAX回调,当你调用的.html()方法来刷新DOM后,你需要解析:

  $('形式')removeData('验证')。
$('形式')removeData('unobtrusiveValidation')。
$ .validator.unobtrusive.parse(形式);

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天全站免登陆