Mixing razor and javascript code for @Html.Partial

2020-02-14 07:05发布

Can anyone provide me solution for how to dynamically add some code into the page in MVC.

I was doing this way but in this code the page fails to identity index javascript variable , as it is not identifying the index javascript variable.

$(document).on('click', '.add-option', function () {           
  var index = $("div.ques-options").size();
  if (index < 5) {
    $('.MainContainer').append('@Html.Partial("_Options", index)')
  }
});

2条回答
姐就是有狂的资本
2楼-- · 2020-02-14 07:33

As mentioned in the answer by Sergey Boiko, this approach is not recommended as you can utilize ajax instead to have the server return the partial view.

Anyhow, mixing javascript and Razor requires that you surround your Razor call with any code block

@{ ... } or @if, etc.

and putting the code itself in an escaped sequence

@: or the <text> tag.

So, knowing this, you can do something like

<script>
    var partialView = '';
    @{
        <text>
            partialView = '@Html.Partial("_Options", index)';
        </text>
     }

     $(document).on('click', '.add-option', function () {           
         var index = $("div.ques-options").size();
         if (index < 5) {
             $('.MainContainer').append(partialView)
      }});
</script>

Check out Mix Razor and Javascript code and Using Razor within JavaScript

查看更多
等我变得足够好
3楼-- · 2020-02-14 07:36

it would be better to use jQuery load() or call by ajax action in the controller, this approach described there ASP.NET MVC rendering partial view with jQuery ajax

查看更多
登录 后发表回答