Search code examples
c#asp.net-mvc-5asp.net-mvc-partialviewmvc-editor-templatesasp.net-mvc-viewmodel

How to use an editor template in different views


I have a sidebar on my website that contains a textbox binded to a viewmodel and needs to be on all of the views of my website. First I created both the viewmodel class and the viewmodel cshtml file (both in the Shared folder):

Class:

namespace CaseLaw.Web.Models.Shared
{
    public class SidebarViewModel
    {
        public string SearchString { get; set; }
    }
}

EditorTemplate:

@model CaseLaw.Web.Models.Shared.SidebarViewModel

<div class="form-group">
    <div class="input-group">

        @Html.TextBoxFor(m => m.SearchString, new { @class = "form-control", placeholder = "Search the Database" })

        <span class="input-group-btn">
            <input type="submit" class="btn btn-default caselawMainbtn" value="Search" />
        </span>
    </div>
</div>

After that, I created a Partial View that calls the EditorTemplate:

@model CaseLaw.Web.Models.Shared.SidebarViewModel

<div class="row caselawSidebarImg">
    <h2 id="caselawTitle">Caselaw</h2>
    <h4 id="caselawSubTitle">The complete database.</h4>
</div>
<div class="row caselawSearchForm">
    <div class="col-sm-12">

        @using (Html.BeginForm("Index", "OpinionDocument", new { SearchString = Model.SearchString }, FormMethod.Get, new { @class = "form-inline" }))
        {
            @Html.EditorForModel()
        }

    </div>
</div>
<div class="row caselawSidebarMenu">
    <div class="col-sm-12">
        <ul>
            <li><a href="#">Dashboard</a></li>
            <li><a href="#">Your Notes</a></li>
            <li><a href="#">Your Bookmarked Cases</a></li>
            <li><a href="#">Your Projects</a></li>
            <li><a href="#">Recently Viewed</a></li>
        </ul>
    </div>
</div>

Then, i called the partial view on one of my views:

 <div class="col-sm-2 caselawSidebar">
       @{Html.RenderPartial("_Sidebar");}
 </div>

The problem, is that that view is binded to another model other than the model needed in the editortemplate inside the partialview, so the application throws an error. How can I send the correct model to the Partialview, and be able to use it throughout my website?

Thanks!


Solution

  • The solution was quite simple: I just needed to create a new object, like this:

     @{Html.RenderPartial("_Sidebar", new CaseLaw.Web.Models.Shared.SidebarViewModel());}
    

    I tried this before and didn't work, the problem was that I forgot to add "new" before the model.