I need to model-bind data from textboxes generated dynamically on the client side (using jQuery .tmpl plugin) so that the data is accessible in my MVC3 controllers. I found code for this at the following link:
This article discusses several approaches alongwith working source code. The last approach is what I want and it works. But it is probably using the webforms view engine (inside JavaScript blocks) or just server side tags. I would appreciate if someone can help me get it working with razor syntax.
In particular I was hoping to get the razor syntax for the following block in the code:
<script type="text/javascript">
<%int idx=0;
foreach (var c in Model){
ViewData["key"]=idx; %>
$("#ClientTemplate").tmpl([{FirstName : "<%: c.FirstName %>",
LastName : "<%:c.LastName %>" ,
idx: <%:idx.ToString() %>}]).appendTo("#ExistingClients");
<% idx++;%>
<%} %>
</script>
<script type="text/javascript">
function removeClient(DivName) {$("#" + DivName).remove();}
var num = <%:Model.Count() %>;
$("#btnAddNewClient").click(function () {
$("#ClientTemplate").tmpl([{FirstName : "",
LastName : "" ,
idx: num}]).appendTo("#NewClients");
num++;
});
</script>
I wasn’t able to get it working in the manner I had thought earlier. I ended up creating a javascript object with the same property names as my C# object and then sending the object to the controller method using a jquery .ajax call.