thestruggleisreal
thestruggleisreal

Reputation: 1295

How to put a Partial View into a div in JavaScript (with jQuery)

I have ,MyPartialView.cshtml':

<div id="partialDiv">some content</div> 

an 'index.cshtml':

<div id="mainDiv"> </div>

and an 'index.js'.

The 'index.js' should do sth like:

$('mainDiv').html($('#partialDiv'))

to put the partial view into the main div.

(writing @<text> <div> @Html.Partial("MyPartialView")</div></text>) in my .cshtml works, but I need to change the content dynamically. Therefore, I thought maybe there is an equivalent in JavaScript for 'Html.Partial'

(Or is there another way to get a Partial View without an AJAX Call)

Upvotes: 2

Views: 5727

Answers (2)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

@Html.Partial("MyPartialView") used only to render single partial view file (also with @Html.RenderPartial()). You can use AJAX to call controller action which returns partial view:

AJAX Request

$.ajax({
    type: 'GET',
    url: '@Url.Action("ActionName", "ControllerName")',
    // other settings
    success: function (result) {
        $('mainDiv').html(result);
    }
});

Controller Action

[HttpGet]
public ActionResult ActionName()
{
    // do something
    return PartialView("MyPartialView");
}

Note that there's no equivalent of calling partial view in JS, because you need to make request to server which can't be simply handled by standard JS functions.

Upvotes: 3

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

cshtml files are rendred in server side. you can't load it using just JavaScript. the perfect way is using Ajax by calling an Action that return your partial view

Upvotes: 2

Related Questions