1

我目前有以下代码:

        [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");
        }

在我看来,我有一个 JavaScript 按钮,它将添加一个div以便用户可以发布另一个页面,例如:

$("#add-page").click(function () {
    $("#page").append('<div id="page"> @Html.TextBoxFor(u => u.PostPages[0].Title) </div>');
});

如何使当用户单击 JavaScript 按钮时,新文本将附加到页面 u.PostPages[x]增加?

4

3 回答 3

3

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...

于 2013-08-05T19:27:31.810 回答
0

要增加 u.PostPages[x] 您可以使用以下代码:

<script>

var i = 0;

$("#add-page").click(function () {
    i++
    $("#page").append('<div id="page"> @Html.TextBoxFor(u => u.PostPages['+i+'].Title') </div>');
});

</script>

这是一个小的工作示例:jsfiddle

于 2013-08-05T19:46:58.637 回答
0

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>');
}); 
于 2013-08-05T20:10:25.937 回答