【问题标题】:MVC 3 Razor. Partial View validation is not workingMVC 3 剃刀。部分视图验证不起作用
【发布时间】:2012-02-28 21:52:55
【问题描述】:

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

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

这是我的模型:

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; }        
}

这是我的控制器:

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

这是我的主视图:

<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

这是我的部分视图,加载到主页的 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>   
}

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 razor


【解决方案1】:

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

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

【讨论】:

  • 唯一的问题是每当我提交表单时都会出错。错误是“Microsoft JScript 运行时错误:无法获取属性 'unobtrusive' 的值:对象为空或未定义”。你可能知道为什么吗? ——
  • 实际上,达林,你的回答很好。显然,该问题是由 Telerik jquery 验证和 Internet Explorer 都存在兼容性问题引起的。在运行 Chrome 时,$.validator.unobtrusive.parse('elementOrForm') 完全符合它的需要:替换丢失的事件处理程序,而不是在运行 Internet Explorer 时抛出“未定义”异常。我还发现,当使用 Internet Explorer 时,在主视图代码之上的这个调用停止了兼容性问题。 Html.Telerik().ScriptRegistrar().jQuery(false).jQueryValidation(false); 非常感谢 bruh!
  • 谢谢,但我必须最后添加$('form').valid(); 以消除部分视图替换时的验证错误。
猜你喜欢
  • 2011-10-12
  • 2013-08-23
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 2011-11-22
  • 1970-01-01
相关资源
最近更新 更多