简体   繁体   中英

jquery load partial view asp.net mvc

i have some header tabs on a basic index.aspx page that uses a masterpage.

the header tabs are correctly rendered on the index page from a viewusercontrol (<% Html.RenderPartial("pvHeaderTabs")%>). the problem is i am trying to load other partial views into the index page without any luck. can someone point out what i am doing wrong?

on the master page i have added the following js code:

$(document).ready(function () {
    $('div.headertabs span').click(function () {
        var tabclass = $(this).attr('class')
        var tabid = $(this).children('a').attr('id')
        if (tabclass.indexOf("selected") == -1) {
            $(this).parent().children('.selected').removeClass('selected');
            $(this).addClass('selected');
            switch (tabid) {
                case "dashboard": $('#MainContent').load('<%= Html.RenderAction("ViewDashboard") %>');
                default: $('#MainContent').load('<%= Html.RenderAction("ViewDashboard") %>');
            }
        }
    });
});

HomeController.vb

Function ViewDashboard() As ActionResult
    Return PartialView()
End Function

See also: This question or this one . I use this solution (also from SO somewhere):

public class OfferController : Controller
{
    [HttpPost]
    public JsonResult EditForm(int Id)
    {
        var model = Mapper.Map<Offer, OfferEditModel>(_repo.GetOffer(Id));

        return Json(new { status = "ok", partial = this.RenderPartialViewToString("Edit", model) });
    }
}



public static partial class ControllerExtensions
{
    public static string RenderPartialViewToString(this ControllerBase controller, string partialPath, object model)
    {
        if (string.IsNullOrEmpty(partialPath))
            partialPath = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;

        using (StringWriter sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, partialPath);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
            // copy model state items to the html helper 
            foreach (var item in viewContext.Controller.ViewData.ModelState)
                if (!viewContext.ViewData.ModelState.Keys.Contains(item.Key))
                {
                    viewContext.ViewData.ModelState.Add(item);
                }


            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM