Mixing razor and java script code for @Html.Partial()

廉价感情. 提交于 2019-12-18 08:56:52

问题


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)')
  }
});

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/24744832/mixing-razor-and-java-script-code-for-html-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!