Multiple models in a view

前端 未结 12 1829
太阳男子
太阳男子 2020-11-21 23:07

I want to have 2 models in one view. The page contains both LoginViewModel and RegisterViewModel.

e.g.

pub         


        
12条回答
  •  粉色の甜心
    2020-11-21 23:35

    This is a simplified example with IEnumerable.

    I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:

    @using DelegatePortal.ViewModels;
    
    @model SearchViewModel
    
    @using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
    {
    
                    Employee First Name
                    @Html.EditorFor(model => model.SearchParams.FirstName,
    new { htmlAttributes = new { @class = "form-control form-control-sm " } })
    
                    
    
    }
    
    @(Html .Grid(Model.Delegates) .Build(columns => { columns.Add(model => model.Id).Titled("Id").Css("collapse"); columns.Add(model => model.LastName).Titled("Last Name"); columns.Add(model => model.FirstName).Titled("First Name"); })

    ... )

    SearchViewModel.cs:

    namespace DelegatePortal.ViewModels
    {
        public class SearchViewModel
        {
            public IEnumerable Delegates { get; set; }
    
            public SearchParamsViewModel SearchParams { get; set; }
    ....
    

    DelegateController.cs:

    // GET: /Delegate/Search
        public ActionResult Search(String firstName)
        {
            SearchViewModel model = new SearchViewModel();
            model.Delegates = db.Set();
            return View(model);
        }
    
        // POST: /Delegate/Search
        [HttpPost]
        public ActionResult Search(SearchParamsViewModel searchParams)
        {
            String firstName = searchParams.FirstName;
            SearchViewModel model = new SearchViewModel();
    
            if (firstName != null)
                model.Delegates = db.Set().Where(x => x.FirstName == firstName);
    
            return View(model);
        }
    

    SearchParamsViewModel.cs:

    namespace DelegatePortal.ViewModels
    {
        public class SearchParamsViewModel
        {
            public string FirstName { get; set; }
        }
    }
    

提交回复
热议问题