Reputation: 5820
Given the following situation:
I have a model that contains various properties, one of those properties is a List. The model is the following:
public class DocumentTypeViewModel : BaseViewModel<int>
{
#region Properties
public string Name { get; set; }
public List<DocumentTypeProperty> Properties { get; set; }
#endregion Properties
}
The DocumentTypeProperty, has just a single field with a name (and off course an id, but that's not important here).
Now, the ActionResult to show the view on which the create will happen is the following:
public ActionResult Create()
{
var model = Mapper.Map<DocumentType, DocumentTypeViewModel>(new DocumentType());
return View(model);
}
So, as you see, I send an empty model to the view, so the collection is null. Now, on in my Razor view i want to have an add button that I can use to add an element to the collection (I know that I can use jQuery to create elements), but I don't want to post it since it's not needed, the post will occur on the save of the model.
So the question is:
How can I pass my dynamiccly created textboxes to my ActionResult?
Kind regards,
Upvotes: 0
Views: 2892
Reputation: 851
If you want to show a IEnumerable/list on your view, you can just usea forech loop.either you can send the list from your controller via viewbag or modelbinding.Something like that
public ActionResult Create()
{
var model = Mapper.Map<DocumentType, DocumentTypeViewModel>(new DocumentType());
Viewbag.List=Userlist// bind your list here
return View(model);
}
Just use a table and a forech loop to represent your list data
@foreach (var item in @Viewbag.List)
{
//Define your table structure
}
And i am not clear what u r saying about your second step for adding data.let me clear first. Thanks
Upvotes: 1
Reputation: 757
The Model Binding in MVC will bind to a collection
@Html.TextBoxFor(model => model[0].Name)
@Html.TextBoxFor(model => model[1].Name)
Then your controller could be
public ActionResult Create(List<DocumentTypeViewModel> )
Then you could create all rows at once when the form is submitted.
If you want to save each row to the database as it is added to the form, then you'll need to do some AJAX.
Also, there's no need to put the DateCreated and the DateUpdated in the view. If you do, then a savvy user would be able to edit them. Just have the controller add them before the save.
Upvotes: 2