0

我一直在一個MVC項目,有一個複雜的模型與幾個嵌套類,一個類有嵌套在其中的另一個類。我可以正確更新所有其他複雜類型,但最後一個複本類型永遠不會正確更新。我已經確保註冊它的自定義模型聯編程序,它被執行並返回一個對象,其中的屬性賦予了適當的值,但原始模型永遠不會被更新。自定義模型綁定器不更新

我剪斷了這樣的作品,我留下唯一的結構下的所有內容:

public class Case 
{ 
    public Case() 
    { 
     PersonOfConcern = new Person(); 
    } 

    public Person PersonOfConcern { get; set; } 
} 

[ModelBinder(typeof(PersonModelBinder))] 
public class Person 
{ 
    public Person() 
    { 
     NameOfPerson = new ProperName(); 
    } 

    public ProperName NameOfPerson { get; set; } 
} 

[TypeConverter(typeof(ProperNameConverter))] 
public class ProperName : IComparable, IEquatable<string> 
{ 
    public ProperName() 
     : this(string.Empty) 
    { } 

    public ProperName(string fullName) 
    { 
     /* snip */ 
    } 

    public string FullName { get; set; } 
} 

模型綁定

public class PersonModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType == typeof(Person)) 
     { 
      HttpRequestBase request = controllerContext.HttpContext.Request; 
      string prefix = bindingContext.ModelName + "."; 

      if (request.Form.AllKeys.Contains(prefix + "NameOfPerson")) 
      { 
       return new Person() 
       { 
        NameOfPerson = new ProperName(request.Form.Get(prefix + "NameOfPerson")) 
       }; 
      } 
     } 

     return base.BindModel(controllerContext, bindingContext); 
    } 
} 

控制器

[HttpPost] 
public ActionResult Edit(int id, FormCollection collection) 
{ 
    if (CurrentUser.HasAccess) 
    { 
     Case item = _caseData.Get(id); 

     if (TryUpdateModel(item, "Case", new string[] { /* other properties removed */ }, new string[] { "PersonOfConcern" }) 
      && TryUpdateModel(item.PersonOfConcern, "Case.PersonOfConcern")) 
     { 
      // ... Save here. 
     } 
    } 
} 

我在我的智慧'結束。 PersonModelBinder得到執行並返回正確的一組值,但模型永遠不會更新。我在這裏錯過了什麼?

+0

你有沒有找到解決這個?我現在有完全相同的問題。 –

+0

嗯,是的......但我通過改變方法解決了問題。我轉而使用了一個基本的ViewModel。現在,我在Model類中嵌套了類,但是我只在ViewModel類中使用.NET基元,並在HttpPost操作中將ViewModel數據映射到模型。如果您想了解更多詳細信息,我可以將其他信息作爲答案發布。 – jwiscarson

+0

太好了,我最終找到了一個類似的解決方法。非常感謝您花時間回覆。 –

回答

0

我想你應該在全球ASAX增加它的Application_Start

ModelBinders.Binders.Add(typeof(PersonModelBinder), new PersonModelBinder()); 
+0

謝謝,但我試過。如果我沒有添加活頁夾,我的自定義模型活頁夾將不會被調用。 – jwiscarson