Reputation: 1080
I currently have the following code:
[HttpPost]
public ActionResult Index(IList<LocalPageModel> postPages,
IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0))
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/"),
fileName);
file.SaveAs(path);
}
}
}
else
{
ManagePagesModel mod = new ManagePagesModel
{
PostPages = postPages
};
return View("Index", mod);
}
return RedirectToAction("Index");
}
In my view, I have a JavaScript button which will add a div
so that the user can post another page such as:
$("#add-page").click(function () {
$("#page").append('<div id="page"> @Html.TextBoxFor(u => u.PostPages[0].Title) </div>');
});
How do I make it so that when the user clicks on the JavaScript button, the new text will be appended to the page and u.PostPages[x]
will be incremented?
Upvotes: 1
Views: 2737
Reputation: 3479
To increment u.PostPages[x] you may use following code:
<script>
var i = 0;
$("#add-page").click(function () {
i++
$("#page").append('<div id="page"> @Html.TextBoxFor(u => u.PostPages['+i+'].Title') </div>');
});
</script>
Here is small working example: jsfiddle
Upvotes: 0
Reputation: 135
You didn't past your view, but I assume you have the following at the top:
@model = ManagePagesModel
If that's the case, you can then use the following @foreach to loop through the page models:
$("#add-page).click(function() {
@foreach(var pageModel in Model.PostPages){
$("#page").append('<div id="page"> @Html.TextBoxFor(u => pageModel.Title) </div>');
});
Upvotes: 0
Reputation: 40393
If you want to do it all on the client (no AJAX), maybe don't use the MVC helpers at all, and do it manually instead - you know the HTML that will be rendered, so just do that:
var i = 0;
$("#add-page").click(function () {
$("#page").append('<input type="text" name="PostPages[' + (i++) + '].Title">');
});
Maybe clean the code up a bit so the quotes don't get too confusing, but you get the idea...
Upvotes: 3