Search code examples
jqueryasp.net-mvc-5partial-viewsasp.net-mvc-partialview

ASP.NET MVC partial views rendering


I'm a beginner in ASP.NET MVC and I want to have a website like this :

  • A main page that load all the css/js files, subscribe to JavaScript events, store JavaScript variables
  • Partial views that replace the page content without reloading it, and keep the JavaScript variables,etc...

What is the best way to to it ?

I tried :

        $.ajax({
            url: '@Url.Action("Index", "Home")',
            data: { cardid: currentCardId },
            cache: false,
            type: "POST",
            dataType: "html",
            success: function (data) {
                SetData(data);
            }
        });

function SetData(data) {
    alert(data);
    $("#divPartialView").html(data);
}

In my HomeController, I return a PartialView();

(It doesn't work yet but it should)

Is there a simple/better way ?

I also tried this but it doesn't work :

$('#divPartialView').load(@Html.Action("Index", "Home")));

Also, Can I define the Model in the PartialView ?


Solution

  • your example should work

    This is a working example

    $.ajax({
          type: 'POST',
          url: '@Url.Action("ActionName", "ControllerName")',
          data: { id: $('#mycomponent').attr('data-id')},
          success: function (data2) {
                        $('#mydiv').html(data2);
                   },
          error: function (a, b, c) {
                alert(a);
          }
    });
    

    my controller

    public ActionResult ActionName(int id)
            {
                return PartialView("mypartialViewPath",id);
            }
    

    partial view

    @model int
    <div>
    ...content
    </div>