2012-02-28 64 views
11

我遇到了問題,我無法從我的部分視圖中啓動客戶端驗證,在用戶單擊按鈕後加載到div中。在這個例子中,我已經停止了「切換」div來查看驗證是否觸發,但無濟於事,沒有任何反應。MVC 3剃刀。部分查看驗證不起作用

幸運的是,該模型不接受任何無效輸入,但它也不會警告用戶實際的錯誤。任何幫助,將不勝感激。

這裏是我的模型:

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> 
} 
+0

的[jQuery的客戶端驗證不MVC3局部視圖工作(HTTP可能的複製。 com/questions/14134949/jquery-client-side-validation-not-working-in-mvc3-partial-view) – Zairja 2016-05-11 23:36:32

回答

32

每當你完成一個AJAX調用,並與您需要將控制器動作返回部分HTML內容替換爲您的DOM的某些部分重新分析客戶端不顯眼的驗證規則。因此,在您成功的AJAX回調,當你調用.html()方法刷新DOM後,你需要解析://計算器:

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

唯一的問題是我每次提交表單時都會收到一個錯誤。錯誤是「Microsoft JScript運行時錯誤:無法獲取屬性的值」不顯眼「:對象爲null或未定義」。你可能知道爲什麼嗎? - – user1238864 2012-02-29 21:08:26

+0

其實,達林,你回答的工作很好。顯然,這個問題是由Telerik jQuery驗證和Internet Explorer兼容性問題引起的。當運行Chrome時,$ .validator.unobtrusive.parse('elementOrForm')'完成它所需的操作:替換丟失的事件處理程序,而不是在運行Internet Explorer時拋出「未定義的」異常。 我還發現,使用Internet Explorer時,在主視圖代碼的頂部調用將停止兼容性問題。 'Html.Telerik()。ScriptRegistrar()。jQuery(false).jQueryValidation(false);' 非常感謝布魯! – user1238864 2012-02-29 21:56:47

+0

謝謝,但我不得不添加'$('form')。valid();'在部分視圖替換時刪除驗證錯誤。 – stom 2016-10-13 09:25:51