How can we include a form in _layout?

2019-08-17 19:19发布

问题:

I currently have a _layout.cshtml used by every page of my website.
I need to put a form on each page displayed as a popin.
So, i created a new PartialView (the content of my form) with its corresponding ViewModel and called it in _layout.cshtml.

However, i have a model conflict between ViewModels of pages using the layout and the ViewModel used by the new form (since we can't have directly two models for the same view).

The model item passed into the dictionary is of type 'XXX', but this dictionary requires a model item of type 'YYY'.

How can we include a form in _layout without this conflict ?

回答1:

The following has worked for me with a sidebar on every page.

  1. Create a controller for your partial view
  2. In that controller, create a method for the view you want to return, and be sure to use the [ChildActionOnly] filter

    public class PartialController : Controller
    {
        [ChildActionOnly]
        public PartialViewResult Alerts()
        {
    
            return PartialView("Alerts", messages);
        }
    }
    
  3. In your _layout view, you'll have the following:

    @Html.Action("Alerts", "Partial")
    

    (instead of @Html.RenderPartial or @Html.Partial)

  4. It sounds like you already have what you need for the view.

I have not used this with a form, but it should work similarly. Hope this helps.