V
V
vily2014-02-24 16:53:37
JavaScript
vily, 2014-02-24 16:53:37

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>


The list will be filtered without reloading the page. I add a script in which, through jquery ajax, I update the list items on a click on the checkbox
$.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);
            });
        }
    });

The submit button submits the selected list items to the server.

Question: how to avoid code duplication in the view and the script? It means to store the structure of ul and each li in one place.

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander S, 2014-02-26
@FirstX

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 question

Ask a Question

731 491 924 answers to any question