Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

asp.net mvc - Adding another "Pet" to a Model Form

Simplified example.

I have a Model which has a few fields:

OwnerFirstName
OwnerLastName
List<Pet> Pets (Pet is a few string fields)

The UI needs to allow the user to add any number of new Pets. The UI for the Pet entry is an MVC template _petEditor.cshtml

Client side, how do I add a new Pet to the Model's Pet collection, then add a new set of fields for the Pet from _petEditor.cshtml ?

When the user submits the form, MVC will get a model with all the Pets added.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use javascript to dynamically create indexed inputs for post back. As an example create a dummy set of inputs that are cloned and displayed when you click an 'add pet' button (assumes Pet properties are displayed in a table with id='Pets')

<div id="NewPet" style="display:none">
  <tr>
    <td><input type="text" name="Pets[#].Type value /></td>
    <td><input type="text" name="Pets[#].Breed value /></td>
    <td>.....</td> // more properties of Pet
    <td><input type="hidden" name="Pets[#].Index" value ="%"/></td>
  </tr>
</div>

Note the use of a dummy indexer to prevent this one being posted back

And the script

$('#AddButton').click(function() {
  var index = (new Date()).getTime(); 
  var clone = $('#NewPet').clone();
  // Update the index of the clone
  clone.html($(clone).html().replace(/[#]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index  + '"'));
  $('#Pets tbody').append(clone.html());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...