Binding conflict between a property named Title in my Model and View.Title in my View (in MVC)

前端 未结 4 948
野性不改
野性不改 2021-01-05 01:50

My Model contains a property named Title, and in my Create view I set the page title using ViewBag.Title.

This creates the fol

4条回答
  •  我在风中等你
    2021-01-05 02:33

    I would recommend using EditorFor instead of Editor.

    Html.EditorFor(x => x.Title)
    

    instead of:

    Html.Editor("Title")
    

    This way not only that the view takes advantage of your view model but it behaves as expected in this case.

    Example with ASP.NET MVC 3.0 RTM (Razor):

    Model:

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

    Controller:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "ViewBag title";
            ViewData["Title"] = "ViewData title";
            var model = new MyViewModel
            {
                Title = "Model title"
            };
            return View(model);
        }
    }
    

    View:

    @model AppName.Models.MyViewModel
    @{
        ViewBag.Title = "Home Page";
    }
    
    @Html.EditorFor(x => x.Title)
    
    @{
        ViewBag.Title = "Some other title";
    }
    

    So no matter how much we try to abuse here the editor template uses the correct model title (which is not the case if we used Html.Editor("Title")).

提交回复
热议问题