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)')
}
});
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
Check out Mix Razor and Javascript code and Using Razor within JavaScript
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