2015-05-11 37 views
-1
public PersonViewModel() 
    { 
     Children = new List<ChildViewModel>(); 
    } 

    [Required(ErrorMessage = "Required!")] 
    public string FName { get; set; } 

    [Required(ErrorMessage = "Required!")] 
    public string LName { get; set; } 

    public List<ChildViewModel> Children{ get; set; } 
} 

    public class ChildViewModel 
{ 
    [Required(ErrorMessage = "Required!")] 
    public string FName { get; set; } 

    [Required(ErrorMessage = "Required!")] 
    public int Age { get; set; } 
} 

我控制器使用ajax調用partial View中的驗證?

public ActionResult Index() 
    { 
     return View(); 
    } 
    [HttpPost] 
    public ActionResult Index(PersonViewModel person) 
    { 
     if (!ModelState.IsValid) 
     { 
      return View(person); 
     } 
     return View(); 
    } 
    public ActionResult AddChildBox(PersonViewModel person,int id) 
    { 
     ViewBag.Counter = id; 
     return PartialView("View"); 
    } 
} 

我通過Ajax調用局部視圖創建視圖顯示兒童對兒童

<script type="text/javascript"> 
    var num = 0; 
    $("#AddChildBtn").click(function() { 

     $.ajax({ 
      type: 'GET', 
      url: '@Url.Content("~/Home/AddChildBox/")', 
      data: { 
       Id: num 

      }, 
      dataType: 'html', 
      success: function (result) { 
       $('#Fields').append(result); 
       num = num + 1; 
      } 
     }); 
    }); 
</script> 

領域與此代碼

@if (Model != null) 
{ 
    for (int i = 0; Model.Child.Count>i;i++) 
    { 
     @Html.Action("AddChildBox", "Home", new { id = i }) 
    } 
} 

和我的部分查看

@model WebApplication4.Models.PersonViewModel 

@{ 
    int i = ViewBag.Counter; 
} 
<div class="form-group"> 
    @Html.LabelFor(model => model.Child[i].FName, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.Child[i].FName, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.Child[i].FName, "", new { @class = "text-danger" }) 
    </div> 
</div> 
<div class="form-group"> 
    @Html.LabelFor(model => model.Child[i].Age, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.Child[i].Age, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.Child[i].Age, "", new { @class = "text-danger" }) 
    </div> 
</div> 

這可行,但是當從AddChildBox中刪除人員操作方法參數時,部分視圖字段的驗證消息不起作用。 我不會在我的動作中使用它,那麼爲什麼我需要它? 我很困惑,誰可以向我解釋在這段代碼中發生了什麼?

+0

當您提交時,您的ChildViewModel列表是否爲空?你的部分不知道你的原始模型,所以它正在創建一個新模型。你可以讓你的孩子成爲一個ChildViewModel的數組,然後在你的部分,只要做''。當你提交時,你的模型現在會有一系列的孩子。 –

回答

1

您的實施有許多問題。您無法驗證動態添加內容的原因是驗證程序在視圖第一次呈現時解析,並且對新內容一無所知。你需要重新解析驗證你已經追加使用

$('form').data('validator', null); 
$.validator.unobtrusive.parse($('form')); 

你的部分觀點不會給真正的2路模型結合新的內容後,我建議你使用BeginCollectionItem助手來解析的部分爲每個項目(refer this article for an example)。幫助器用Guid替換基於零的索引器,併爲匹配的Index值呈現額外的隱藏輸入,允許非連續的索引集合成功綁定(即允許您動態刪除視圖中的項目)。

純客戶端替代方案顯示在this answer