动态添加项目到集合

时间:2011-07-02 19:36:16

标签: jquery asp.net-mvc-3 razor

我有一个向集合中添加元素的视图: 它将我的元素添加到html中,但是当我调用ActionResult时,Model.TagModelsis仍为空(在开始时为空)。

<div id="tags_div">
            <label id="add_tag">Hello</label>
            @foreach (var item in Model.TagModels)
            { 

                <div class="editor-field">
                    @Html.EditorFor(model => item.Name)
                    @Html.ValidationMessageFor(model => item.Name)
                </div>

            }</div>

        <script type="text/javascript">
            $(document).ready(function () {
                var $newdiv1 = $('<div class="ui-button-text"><input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="b" /><span class="field-validation-valid" data-valmsg-for="item.Name" data-valmsg-replace="true"></span></div>');
                $("#add_tag").live("click", function () {
                    $(this).append($newdiv1);
                    return false;
                });
            });
        </script>

这是我的viewmodel:

public class QuestionTagViewModel
    {
        public QuestionModel QuestionModel { get; set; }

        //private List<TagModel> _tagModels=new List<TagModel>(){new TagModel(){Name = "a"},new TagModel(){Name = "b"}};
        private List<TagModel> _tagModels = new List<TagModel>();

        public List<TagModel> TagModels
        {
            get { return _tagModels; }
            set { _tagModels = value; }
        }
    }

为什么模型没有更新? 当我为静态元素更改其他属性时,一切正常

修改 致MHollis:

感谢Anton的回复:)

现在我有了

<script type="text/javascript">
            $(document).ready(function () {
                $("#addItem").click(function () {
                    $.ajax({
                        url: this.href,
                        cache: false,
                        success: function (html) { $("#tags_div").append(html); }
                    });
                    return false;
                });
            });
        </script>

并且tags_div:

<div id="tags_div">
            <label id="add_tag">Hello</label>
            @Html.ActionLink("Add another...", "BlankEditorRow", null, new { id = "addItem" })

            @foreach (var item in Model.TagModels)
            { 

                <div class="editor-field">
                    @Html.EditorFor(model => item.Name)
                </div>

            }</div>

PartialViewResult方法:

public PartialViewResult BlankEditorRow()
        {
            var x=PartialView("TagRow", new TagModel());
            return x;
        }

和部分观点:

@*@using Szamam.Models
@model TagModel

<div class="editor-field">
    @Html.EditorFor(model => model.Name)
    @Html.ValidationMessageFor(model => model.Name)
</div>*@


<div class="editor-field">
<input class="text-box single-line" id="[0].Name"  name="[0].Name" type="text" value="b" />
</div>

元素正在添加但是当fie actionresult时,集合为空:/

所以应该有另一个原因:/

1 个答案:

答案 0 :(得分:2)

这是因为您通过javascript添加的输入的id为“item_name”,名称为“item.name”。他们需要名称为“TagModels [0] .Name”,“TagModels [1] .Name”,“TagModel [2] .Name”。 注意:这是关于here

的信息

<强>更新

好的,所以我继续并根据您提供的数据花时间完成这项工作。值得庆幸的是,我正在为我正在进行的项目提供类似的东西,不幸的是我的项目是在VB.Net中,但是为了帮助你我在C#中做了这个代码(显然)。 注意:除了缺少using语句之外,您可以将此代码复制并粘贴到一个干净的项目中。

视图

@model MvcApplication1.Models.QuestionTagViewModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            var re = /\[(.*?)\]/ ;
            $("#add_tag").click(function() {
                var name = $(".tagRows:last>input").attr("name");
                var m = re.exec(name);
                var itemNumber = parseInt(m[1]) + 1;
                var $newdiv1 = $('<div class="tagRows"><input class="text-box single-line" id="TagModels' + itemNumber + '__Name" name="TagModels[' + itemNumber + '].Name" type="text"><span class="field-validation-valid" data-valmsg-for="TagModels[' + itemNumber + '].Name" data-valmsg-replace="true"></span></div>');
                $(".tagRows:last").after($newdiv1);
                return false;
            });
        });
    </script>
    <title>TagsTest</title>
</head>
<body>
    @using (Html.BeginForm())
    { 
        <div id="tags_div">
            <label id="add_tag">
                Hello</label>
            @for (int i = 0; i < Model.TagModels.Count; i++)
            {
                <div class="tagRows">
                    @Html.EditorFor(model => model.TagModels[i].Name)
                    @Html.ValidationMessageFor(model => model.TagModels[i].Name)
                </div>
            }
        </div>
        <input type="submit" name="submit" value="Submit" />
    }
</body>
</html>

模型

namespace MvcApplication1.Models
{
    public class QuestionTagViewModel
    {

        //private List<TagModel> _tagModels=new List<TagModel>(){new TagModel(){Name = "a"},new TagModel(){Name = "b"}};
        private List<TagModel> _tagModels = new List<TagModel>();

        public List<TagModel> TagModels
        {
            get { return _tagModels; }
            set { _tagModels = value; }
        }
    }

    public class TagModel
    {
        public string Name { get; set; }
    }
}

控制器

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult TagsTest()
        {
            var tagmodels = new List<TagModel>();
            tagmodels.Add(new TagModel() { Name = "Tag1" });
            tagmodels.Add(new TagModel() { Name = "Tag2" });
            tagmodels.Add(new TagModel() { Name = "Tag3" });
            var model = new QuestionTagViewModel() { TagModels = tagmodels };


            return View(model);
        }

        [HttpPost]
        public ActionResult TagsTest(QuestionTagViewModel model)
        {
            return null;
        }
    }
}