Dynamically build a collection prior to form post using jQuery in asp.net mvc 2
In my object g开发者_Go百科raph, I have a standard parent + children relationship. Say something like,
Cat.Kittens = new HashSet<Cat>();
When I have a form for a new Cat, I want to add zero-or-many kittens prior to clicking the save button. Since it's a new Cat, I also don't want to post the kitten to the server yet (i.e. using AJAX or the like; I just want to do one big dump to the server with the save button). I'm trying to figure out the best way to do this with some efficiency but am coming up short on Google. Someone has to have done this already.
I'm less concerned about whether the parent Cat is new or not; if I have to push the kitten addition off to an Edit form, so be it. The issue for me is how to dynamically add multiple kittens on the client and subsequently be able to massage the collection in the controller prior to storing the data.
Any ideas? Good examples? jQuery + asp.net mvc 2 is the stack.
Thanks in advance!
It can be done in one form I have done this where I will keep a blank kitten input form hidden on the page then copy it with jquery when the client says add another kitten.
The controller is where it gets a little tougher
public class Cat
{
public string name { get; set; }
public List<Kitten> Kittens { get; set; }
}
public class Kitten
{
public int id { get; set; }
public string color { get; set; }
public string CatName { get; set; }
}
Controller
public ActionResult AddCat()
{
return View();
}
[HttpPost]
public ActionResult AddCat(Cat c)
{
var sb = new StringBuilder();
sb.Append(c.name);
sb.Append("kittens are : " + Request.Form["color"]);
return Content(sb.ToString());
}
View
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Kittens.Models.Cat>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
AddCat
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<h2>
AddCat</h2>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.name) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.name) %>
<%: Html.ValidationMessageFor(model => model.name) %>
</div>
<table id="kittenDest">
<tr>
<td colspan="2">
<input id="Button1" type="button" value="add Kitten" />
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
<table id="kittenForm" style="display: none;">
<tr>
<td>
<input id="color" name="color" value="" type="text" />
</td>
</tr>
</table>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#Button1").click(function () {
$("#kittenDest").append($("#kittenForm").html());
});
});
</script>
精彩评论