Answer the question
In order to leave comments, you need to log in
How to avoid code duplication in JS and HTML (Razor) in ASP.NET MVC?
Good afternoon!
The page has a list (ul) with li = checkbox + label + hidden (id) elements. There is also a checkbox that should filter the list items:
@Html.CheckboxFor(m=>m.Filter)
<ul>
@for (int i = 0; i < Model.Data.Count(); i++)
{
<li>
@Html.HiddenFor(m=>m.Data[i].Id)
@Html.CheckBoxFor(m=>m.Data[i].Checked)
@Html.DisplayFor(m=>m.Data[i].Name)
</li>
}
</ul>
$.ajax({
url: '/Controller/GetData',
dataType: 'json',
traditional: true,
data: { filter: checked},
success: function(data) {
dataList.empty();
$.each(data, function(index, item) {
var listItem = $('<li></li>');
var hidden= $('<input></input>', {
//init hidden data
'type' : 'hidden'
});
var checkbox = $('<input></input>', {
//init checkbox data
'type' : 'checkbox'
});
var label = $('<span></span>', {
// init label data
});
listItem.append(hidden);
listItem.append(checkbox);
listItem.append(label);
dataList.append(listItem);
});
}
});
Answer the question
In order to leave comments, you need to log in
The only way to get rid of such "duplication" is
1. either completely move the formation of the html markup of the desired section to javascript / jquery code (jqGrid example)
2. or completely move it to the server method that generates a partial view with the desired data model
Otherwise, you are in a situation when you can put absolutely any html markup on the page, but you don’t want to learn the program code and tell it what you actually have there and how to work with it. This can be done only in a clear and unambiguous structure, where there are certain patterns that can be parsed and analyzed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question