2012-06-21 83 views
0

我有一個容器和嵌套的viewmodels和使用EditorFor呈現嵌套的viewmodels,我想要驗證添加到一個viewmodel(ConcreteViewModelA :: prop3)屬性之一的remoteAttribute。但是,在驗證Controller操作方法中,我所得到的都是null。我試過使用Validate([Bind(Prefix =「item」)] string prop3),但仍然返回爲NULL。有任何想法嗎?RemoteAttribute與前綴

public class SomeContainer 
{ 
    public List<ISomethingViewModel> SomeViewModels { get; set; } 
} 

public class ConcreteViewmodelA : ISomethingViewModel 
{ 
    public int prop1 { get; set; } 
    public int prop2 { get; set; } 
    [Remote("Validate", "RemoteValidation")] 
    public string prop3 { get; set; } 
} 

public class ConcreteViewModelB : ISomethingViewModel 
{ 
    public int prop1 { get; set; } 
    public int prop2 { get; set; } 
} 

public interface ISomethingViewModel 
{ 
    int prop1 { get; set; } 
    int prop2 { get; set; } 
} 

查看:

@model test.Models.SomeContainer 

@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary() 
    <p>Begin here</p> 
    foreach (var item in Model.SomeViewModels) 
    { 
     @Html.EditorFor(x => item) 
    }   
} 
+0

我能得到這個利用工作:公共JsonResult驗證([綁定( Prefix =「item」)] ConcreteViewmodelA vm3) – user965160

回答

2

嘗試定義視圖模型:

public class MyViewModel 
{ 
    public string Prop3 { get; set; } 
} 

然後:

public ActionResult Validate([Bind(Prefix = "item")] MyViewModel model) 
{ 
    return Json(
     !string.IsNullOrEmpty(model.Prop3), 
     JsonRequestBehavior.AllowGet 
    ); 
} 
0

檢查與螢火蟲。你的URL請求看起來像這樣Validate?item.prop3=

所以,你可以做這樣的事情來讀取值

public ActionResult Validate(string prop3) 
    { 
     string prop3Val = Request.QueryString["item.prop3"].ToString(); 

     //your operations with prop3Val 
     return Json(prop3Val, JsonRequestBehavior.AllowGet); 
    } 

enter image description here

+0

是的,螢火蟲顯示URL爲:[link]驗證?item.prop3 = hello – user965160