I'm new to MVC and wanted to know how we can create controls dynamically in MVC3? In my case the situation is there is a form where candidate enters his job experience and he can add multiple entries based on how many companies he has worked before. So the set of controls where user enters details needs to be dynamically added when user says "Add another".
I googled bit but couldn't get much apart from creating controls using jquery. My main problem is how to render controls dynamically and then get their values while submitting the form.
It would be great if anyone can suggest some samples/tutorials on this?
You're obviously coming from Asp.net WebForms background hence having a bit of a problem comparing MVC with WebForms.
Adding additional HTML elements is simply done on the client because it's fast, convenient and doesn't require server side state preservation. And because there's (almost) no need to load these on the server. As you've probably found out, Asp.net MVC works completely differently from Asp.net WebForms.
So the simplest way is to have template loaded on the client and then add new items based on that particular template. This JSFiddle shows you how. If you can't provide template in the HTML you can always load it via Ajax, but that should only be done whenever there's either:
.tmpl
provides conditionals and loops, so we should use these whenever possible).Basically I've used jQuery and its .tmpl()
plugin to quickly generate complex items (by complex I mean not consisting of a single HTML element) with correct naming and IDs and so on. Control names correspond to how Asp.net MVC works. These generated fields would easily model bind to this controller action method:
public ActionResult Experiences(Experience experience)
{
// do what's appropriate
}
Related classes used in this code (only relevant properties):
public class Experience
{
[Required]
public IList<Company> Companies { get; set; }
...
}
public class Company
{
[Required]
public string Name { get; set; }
...
}
IList<T>
is the idea hereBasically whenever you're model binding to IList<T>
(which basically is happening when you're dynamically adding new and new controls) you're having a bit of a problem that needs to be solved on the client with proper input form naming. You can read all the details related to this in my blog post as well where I explain the problem and provide a solution somewhat similar to this.
Important: Instead of linking to a CDN with jQuery
.tmpl()
I had to copy the minimized version of it directly into HTML part in JSFiddle example, because otherwise it won't load the plugin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With