How to dynamically create / delete elements and allow model binding to impact?

I have done this in the past, and I may have to do it again, but before I do this, I want to throw it there to see how people deal with it.

Shaver Type:

<ul>
   @Html.EditorFor(model => model.Questions)
</ul>

What can produce:

<ul>
   <li><input type="text" id="Questions_0__Title" name="Questions[0].Title" value="hi"/></li>
   <li><input type="text" id="Questions_1__Title" name="Questions[1].Title" value="hi2"/></li>
<ul>

Pretty dead just.

Now I need to allow the user to add, edit or delete any of these "Questions".

, . /, jQuery, , "id" "name" (, , , 1 ..).), " " (, , "id" "name" -1 ).

, , .

, , , AJAX , , / . , " ". , jQuery, .

- ?

+3
3

, , JS.

  • 100 . , "", css ""
  • , , "" css.
  • CSS, , "" css.
  • " ", "" .
  • "", "" .

, .

-4

. , , , :

public class QuestionListModel
{
    public IList<QuestionModel> Questions { get; set; }

    public IList<QuestionModel> Template
    {
        get
        {
            return new List<QuestionModel>
                       {
                           new QuestionModel {/* defaults for new question */}
                       };
        }
    }

    public QuestionListModel()
    {
        Questions = new List<QuestionModel>();
    }
}

Template, IEnumerable<T> , . , - MVC. , , "Questions_0__Title", "Template_0__Title".

.

, , <div>. Count . , <div> , . , - :

<div class="templateContainer">
  <div class="question">
    [Template]
  </div>
</div>
<div class="items">
  [for each of your items]
  <div class="question">
    [Question]
  </div>
</div>

, , javascript:

  • , .

        var counter = $("#QuestionsListCount");
        var count = parseInt(counter.val());
        count++;
    
  • , (, jquery .clone(true)), ( 1, ), , .

        var template = $("#templateContainer");
        var newItem = template.clone(true);
        var newId = "item_" + count;
        var newQuestion = newItem.children().first();
        newQuestion.attr("id", newId);
        newQuestion.appendTo('#items');
    
  • , ( , ), ids = > "Template_0" "Questions__count 2" names = > "Template [0]" with "Questions [count from step 2]".

        $("#" + newId + " :input").each(function (index, input) {
            input.id = input.id.replace("Template_0", "Questions_" + (count - 1));
            input.name = input.name.replace("Template[0]", "Questions[" + (count - 1) + "]");
        });
    
  • = > counter.val(count);

  • ...
  • !

, , , ViewModel IsDeleted, . , , ( ), IsDeleted true. , ( , ).

, . , , , (, ).

, ( ) .

!

+2

, ?

, , , , , deletedIds. , :

data-rowId='@Model.Id'

, delete, css , , :

var deletedIds = [];
$('myselector').each(function(){ deletedIds.push($(this).attr('data-rowId'));});
$('deletedIds').val(deletedIds.join(','));

.

, , , , , .

0

All Articles