0

MVC の追加/編集フォームにテキスト ボックスを動的に追加したいと考えています。

「 」というフィールドがあり、ユーザーは「 」テキスト ボックスInterestsをクリックして、好きな興味をいくつでも追加できるはずです。Add another

これは、JQuery を使用して実行できます。

上記のフィールド ' ' からカンマ区切りの値を持つ文字列を生成したいと考えていますInterests

ユーザーが、値のテニス、サッカー、野球の 3 つのテキスト ボックスを追加するとします。Model.Interestこれらの値をコンマ区切りの文字列に結合し、 User モデルのフィールドの 1 つであるに渡したいと思います。

これを行う簡単な方法はありますか..

4

2 に答える 2

3

それよりもはるかに簡単です。入力に name='' 規則を追加するだけで、mvc のバインダーが値を取得します。

実際には 2 つのオプションがあります... 1. name="textbox[0].Name" など。2. 独自の Binder を作成し、必要に応じて入力をバインドします。何も再発明する必要はありません。

私の回答を編集するのに時間がかかってすみません、ここに例があります: モデル:

public class Person
{
    public Person()
    {
        InterestList = new List<Interest>();
    }

    public IList<Interest> InterestList { get; set; }
}

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

バインダー:

public class InterestListBinder: IModelBinder
{
    public object BindModel(ControllerContext controllerContext, 
        ModelBindingContext bindingContext)
    {
        var person = new Person();
        foreach (var i in controllerContext.RequestContext.HttpContext.Request.Form.AllKeys)
        {
            person.InterestList.Add(new Interest
                {
                    Name = controllerContext.RequestContext.HttpContext.Request.Form[i]
                });
        }
        return person;
    }
}

バインダーをアタッチする Global.asax

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        ModelBinders.Binders.Add(typeof(Person), new InterestListBinder());
    }
}

コントローラー:

   public class HomeController : Controller
   {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Person person)
        {
            return View("Index", person);
        }
    }

そして今、ビュー:

@model Data.Services.DataBinders.Person



<div>
    <form action="@Url.Action("Index", "Home")" method="POST">
        @{
            if (Model != null && Model.InterestList.Any())
            {
                foreach (var tb in Model.InterestList)
                {
                    <input type="text" value="@tb.Name"/>
                }
            }
        }
        <input type="button" value="add" id="add" />
        <input type="button" value="remove" id="remove" />
        <input type="submit" value="Submit" />
    </form>
</div>

動的入力を生成する JavaScript には、好きな名前を付けることができます。

    <script>
    (function ($) {
        var demo = {
            init: function () {
                this.elements = null;
                this.cache();
                this.bindEvents();
                return this;
            },
            cache: function () {
                this.elements = new Array();
            },
            bindEvents: function () {
                $("#add").on("click", this.add);
                $("#remove").on("click", this.remove);
            },
            add: function () {
                var self = demo;
                var $elem = $("<input type='text' \>");
                self.elements.push($elem);
                self.render();
            },
            remove: function () {
                var self = demo;
                $.each(self.elements, function (index, elem) {
                    elem.remove();
                });
                self.elements.splice(0, 1);
                self.render();
            },
            render: function () {
                var self = demo;
                for (var e in self.elements) {
                    self.elements[e].attr("name", "Interest" + e);
                    $("form").append(self.elements[e]);
                }
                console.log(self.elements);
            }
        };
        window.load = demo.init();
    })(jQuery)
</script>
于 2013-02-22T04:31:15.077 に答える
2

すべてのテキストボックスがクラスを共有しているtxtInterestsToGrab場合は、それらをすべてコンマ区切りの文字列に結合して、次のような架空のアクションメソッドに投稿できます。saveInterests

    var data = $('.txtInterestsToGrab').val().join(',');



    $.ajax({
        type: "POST",
        url: "/Stuff/saveInterests/",
        dataType: 'json',
        traditional: true,
        data: data,
        success: function () {
        }
    });

カンマ区切りの文字列を使用せず、代わりにリストを使用する場合(これは非常に非常に強くお勧めします)

    var data = $('.txtInterestsToGrab').val();
于 2013-02-22T04:25:35.580 に答える