簡體   English   中英

發布表單時控制器中的模型綁定-為什么使用視圖模型而不是域模型中的類?

[英]Model binding in controller when form is posted - why to use view model instead of class from domain model?

我仍然對ASP.NET MVC 3還是相當陌生。我遇到過視圖模型及其用於將數據從控制器傳遞到視圖的用途。 在我最近關於模型綁定的問題中,兩位專家建議我也應將視圖模型也用於模型綁定。

這是我以前從未遇到過的事情。 但是,兩個人都向我保證,這是最佳實踐。 有人可能會闡明為什么視圖模型更適合於模型綁定的原因?

這是一個示例情況:我的域模型中有一個簡單的類。

public class TestParent
{
    public int TestParentID { get; set; }
    public string Name { get; set; }
    public string Comment { get; set; }
}

這是我的控制器:

public class TestController : Controller
{
    private EFDbTestParentRepository testParentRepository = new EFDbTestParentRepository();
    private EFDbTestChildRepository testChildRepository = new EFDbTestChildRepository();

    public ActionResult ListParents()
    {
        return View(testParentRepository.TestParents);
    }

    public ViewResult EditParent(int testParentID)
    {
        return View(testParentRepository.TestParents.First(tp => tp.TestParentID == testParentID));
    }

    [HttpPost]
    public ActionResult EditParent(TestParent testParent)
    {
        if (ModelState.IsValid)
        {
            testParentRepository.SaveTestParent(testParent);
            TempData["message"] = string.Format("Changes to test parents have been saved: {0} (ID = {1})",
                                                        testParent.Name,
                                                        testParent.TestParentID);
            return RedirectToAction("ListParents");
        }
        // something wrong with the data values
        return View(testParent);
    }
}

因此,在HTTP POST到達時調用的第三個action方法中,我使用TestParent進行模型綁定。 感覺很方便,因為生成HTTP POST請求的瀏覽器頁面包含TestParent所有屬性的輸入字段。 我實際上認為這也是Visual Studio為CRUD操作提供的模板的工作方式。

但是,我得到的建議是第三個操作方法的簽名應讀取public ActionResult EditParent(TestParentViewModel viewModel)

起初聽起來很吸引人,但是隨着您的模型和視圖操作變得越來越復雜,您開始看到對大多數(尤其是所有輸入)使用ViewModels的價值,尤其是輸入場景。

  • 情況1-大多數Web框架容易發布過多信息。 如果直接綁定到域模型,則很有可能會過度發布數據並惡意更改不屬於用戶的內容。 我發現綁定到輸入視圖模型比白名單或黑名單的長字符串列表更干凈,盡管綁定接口還有一些其他有趣的方式。

  • 案例2-隨着您輸入的復雜性增加,您會遇到有時需要不直接在域模型中提交和驗證字段的麻煩(“我同意”復選框等)

  • 案例3-更多的是個人的事情,但是我發現綁定到關系域對象的模型有時會非常痛苦。 與使用MVC的Modelbinder處理復雜的對象圖相比,在AutoMapper中將它們鏈接起來更容易。 與深層關系模型相比,MVC的html幫助器在處理原始類型時也更加順暢。

使用ViewModels的缺點是它不是很干。

因此,故事的寓意是,綁定域模型對於簡單的事情可能是可行的解決方案,但是隨着復雜性的增加,擁有一個單獨的視圖模型然后在兩者之間進行映射變得更加容易。

暫無
暫無

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

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