簡體   English   中英

之間的區別

[英]Difference between

我正在通過電子郵件和密碼創建一個簡單的登錄頁面。 我有一個類LoginViewModel,它將一個User類作為其中的成員變量。 該類包含emailAddress。 密碼位於主LoginViewModel中。 我的User類引用如下:

public User User { get; set; }

當用戶填寫電子郵件地址和密碼並點擊提交時,LoginViewModel會正確地將字段綁定到視圖中User類內的電子郵件地址:

@Html.TextBoxFor(m => m.User.Email) // m is the LoginViewModel model

我想知道為什么它不起作用如果我上面的代碼看起來像這樣:

public User User = new User();

它將User實例中的電子郵件顯示為空值。 我知道構造函數的使用可能比兩者都好,但這兩者之間有什么區別。

編輯#1:在“登錄”操作方法上發布時,會找到我為模型中的電子郵件字段輸入的值:

public User User { get; set; }

這個不是:

public User User = new User(); // --> because of this email field value shows up null

這是DefaultModelBinder一個功能,它只會綁定屬性與公共getter / setter。 如果您瀏覽源代碼,該過程包括初始化模型的新實例,然后嘗試設置其屬性的值。 這里的關鍵部分是

protected virtual void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
{
  ...
  if (!propertyDescriptor.IsReadOnly && !isNullValueOnNonNullableType)
  {
    ...
    propertyDescriptor.SetValue(bindingContext.Model, value) // this is where the value is set
    ...
  }
  ...
}

當你使用public User User = new User(); 您只創建一個字段,其PropertyDescriptorIsReadOnly屬性將返回false因此if塊中的代碼永遠不會執行, User.Email值為nullstring的默認值)

I want to know why it doesn't work if I had the code above looked like this instead:

public User User = new User();

因為基礎結構會查找set方法。 它需要是公共二傳手的財產。

@Stephen提供的代碼安靜並沒有描述問題的核心。 這是DefaultModelBinder的方法,它嘗試綁定模型的屬性。

private void BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
     IEnumerable<PropertyDescriptor> properties = GetFilteredModelProperties(controllerContext, bindingContext);
     foreach (PropertyDescriptor property in properties)
     {
          BindProperty(controllerContext, bindingContext, property);
     }
}

在這里,我們看到GetFilteredModelProperties試圖通過方法調用TypeDescriptor.GetProperties獲取通過methos調用鏈最終得到的PropertyDescriptor ,它返回類型而不是字段的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM