0

Can you tell me how to append the line @Html.Partial("_Layout") to <div class="demo"> by jQuery?

I have tried it, but it doesn't work:

<input type="button" id="btn" value="Click me" />
<div class="demo">
</div>

jQuery code:

$('#btn').click(function(){
     $('.demo').append('@@Html.Partial("_Layout")');
     $('.demo').html($('.demo').text());
});

But the result I received was:

<div class="demo">
     @Html.Partial("_Layout")
</div>

Browser understood that @Html.Partial("_Layout") is a plain text, not a Razor syntax.

Please tell me how to fix it? Many thanks!!!

3
  • why @@Html.Partial("_Layout") 2 '@'? it is just a copy paste problem? Commented Jul 20, 2015 at 19:18
  • @Infer-On Because that's jQuery syntax inside .cshtml file. If one, it will throw error. Commented Jul 20, 2015 at 19:20
  • 3
    By the time your js executes, it's too late to add things to the page with Razor. Razor is processed on the server side before the page is sent to the client Commented Jul 20, 2015 at 19:20

2 Answers 2

4

The @Html.Partial("_Layout") will be resolved at server side, not client side. If you need to load dynamically you should provide a Action and use the jquery $ajax function:

1) At your controller:

public ActionResult Layout()
{
  return PartialView('_Layout');
}

2) At your view

$('#btn').click(function(){
  $.ajax({
    url: '/Controller/Layout',
    dataType: "html",
    success: function (data) {
    $('.demo').html(data);
   }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

0

The @@ will be interpreted by razor engine as the character '@'.

In my opinion, it will be better if you call using ajax the view _Layout and the result you can publish it inside the div demo.

sample:

<input type="button" id="btn" value="click me"/>
<div id="demo"></div>
<script>
$('#btn').on('click',function(){
    e.preventDefault();
    $.ajax({
      url:'@Url.Action("PartialLayout")',
      type: 'post' // according to haack and scott hanselmen, its recommended to use post in the ajax call
    }).done(function(result){
         $('#demo').html(result);
    });
});
</script>

// in your controller you code this one

[HttpPost]
public ActionResult ParitalLayout()
{
     return PartialView("_Layout");
}

I hope this code will help you

Comments

Your Answer

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