1

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 ?

1
  • 1
    Your first example should work, and is the best method IMO. Have you checked the console for errors? Commented May 15, 2014 at 10:04

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Ok it seems to work, but I have a bool variable in my JavaScript. If I do an alert of the variable before "$("#divPartialView").html(data);", it displays "true". but after, when I do the alert from the partial view, it displays "false... Do you have an idea why ?
@Gab which is the variable? can I see the code? remember that the variable exist only in the success context
I have a layout file. In the layout, I initialize the variable : "var myVariable = false", and in a div, I have "@RenderBody()" Then I have my main View that use this layout. I set the variable to true, then I call the ajax function and alert the variable from my partial view. It's like if the page was reloaded... If I initialize the variable directly in my main View and not in the layout, it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.