asp.net Html Dynamic,html - ASP.NET MVC Dynamic Forms - Stack Overflow

If you need to have some dynamic fields in your form, the best way for you would be to use some advanced javascript frameworks like Angular, Backbone, Knockout etc.

If you need something more or less simple it is enough for you to use Knockout. For more advanced scenarios I would recommend Angular, but this is my personal preference.

Here is a simple implementation of a dynamic form with Knockout:

var model = {

users: ko.observableArray(),

addUser: function() {

this.users.push({ name: ko.observable() });

}

};

ko.applyBindings(model);

Add user

Now, what about ASP.NET MVC?

This is more tricky. Perhaps the best and the easiest way would be to use Ajax and post JSON to ASP.NET MVC Action. First of all, you'll need to get a JSON object from your form. With knockout it's very simple:

var json = ko.toJSON(model);

Now, when we know how to get JSON from form, next step is to send your data to an Action. jQuery is perfect for that:

$.ajax({

type: "POST",

url: "@Url.Action("AddUser")",

data: ko.toJSON(model).users, // Serialize to JSON and take users array

accept: 'application/json',

success: function (data) { alert("Done!"); } // Your success callback

});

In our case we basically send an array of strings, thus ASP.NET MVC action should look like that:

[HttpPost]

public JsonResult AddUser(List users)

{

return Json(data); // return something

}

This is definitely not the only one option of how to implement dynamic forms, but I think it's pretty effective. Hope it helps.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值