Html ASP.NET MVC 动态表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17229514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Dynamic Forms
提问by Andrei
Can anyone suggest a good way to develope dynamic forms with ASP.NET MVC?
任何人都可以提出一种使用 ASP.NET MVC 开发动态表单的好方法吗?
I have cascading dropdowns on the page (options in the dropdown depends on the value, selected in the previous dropdown).
我在页面上有级联下拉列表(下拉列表中的选项取决于在上一个下拉列表中选择的值)。
All the values come from the database.
所有的值都来自数据库。
How can I implement such behavior using ASP.NET MVC?
如何使用 ASP.NET MVC 实现此类行为?
Of course I'd like to receive all the values in the controller when I submit my form.
当然,我希望在提交表单时收到控制器中的所有值。
采纳答案by Andrei
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, Knockoutetc.
如果您需要在表单中包含一些动态字段,最好的方法是使用一些高级 javascript 框架,如Angular、Backbone、Knockout等。
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.
如果您需要一些或多或少简单的东西,使用 Knockout 就足够了。对于更高级的场景,我会推荐 Angular,但这是我个人的偏好。
Here is a simple implementation of a dynamic form with Knockout:
这是使用 Knockout 的动态表单的简单实现:
var model = {
users: ko.observableArray(),
addUser: function() {
this.users.push({ name: ko.observable() });
}
};
ko.applyBindings(model);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: users">
<input type="text" data-bind="value: name" /><br />
</div>
<button data-bind="click: addUser">Add user</button>
<ul data-bind="foreach: users">
<li data-bind="text: name"></li>
</ul>
Now, what about ASP.NET MVC?
现在,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:
这更棘手。也许最好和最简单的方法是使用 Ajax 并将 JSON 发布到 ASP.NET MVC Action。首先,您需要从表单中获取一个 JSON 对象。淘汰赛非常简单:
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. jQueryis perfect for that:
现在,当我们知道如何从表单中获取 JSON 时,下一步是将您的数据发送到一个操作。jQuery非常适合:
$.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:
在我们的例子中,我们基本上发送一个字符串数组,因此 ASP.NET MVC 操作应该如下所示:
[HttpPost]
public JsonResult AddUser(List<string> 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.
这绝对不是如何实现动态表单的唯一选择,但我认为它非常有效。希望能帮助到你。
回答by mcintyre321
You can do this very easily using my FormFactorylibrary.
您可以使用我的FormFactory库轻松完成此操作。
By default it reflects against a view model to produce a PropertyVm[]
array:
默认情况下,它会根据视图模型进行反射以生成PropertyVm[]
数组:
```
``
var vm = new MyFormViewModel
{
OperatingSystem = "IOS",
OperatingSystem_choices = new[]{"IOS", "Android",};
};
Html.PropertiesFor(vm).Render(Html);
```
``
but you can also create the properties programatically, so you could load settings from a database then create PropertyVm
.
但您也可以以编程方式创建属性,因此您可以从数据库加载设置,然后创建PropertyVm
.
This is a snippet from a Linqpad script.
这是来自 Linqpad 脚本的片段。
```
``
//import-package FormFactory
//import-package FormFactory.RazorGenerator
void Main()
{
var properties = new[]{
new PropertyVm(typeof(string), "username"){
DisplayName = "Username",
NotOptional = true,
},
new PropertyVm(typeof(string), "password"){
DisplayName = "Password",
NotOptional = true,
GetCustomAttributes = () => new object[]{ new DataTypeAttribute(DataType.Password) }
}
};
var html = FormFactory.RazorEngine.PropertyRenderExtension.Render(properties, new FormFactory.RazorEngine.RazorTemplateHtmlHelper());
Util.RawHtml(html.ToEncodedString()).Dump(); //Renders html for a username and password field.
}
```
``
Theres a demo sitewith examples of the various features you can set up (e.g. nested collections, autocomplete, datepickers etc.)
有一个演示站点,其中包含您可以设置的各种功能的示例(例如嵌套集合、自动完成、日期选择器等)
回答by Roman Bats
You can use FormCollectionas a parameter to receive all data that comes from the form:
您可以使用FormCollection作为参数来接收来自表单的所有数据:
[HttpPost]
public ActionResult ActionName(FormCollection collection)
{
//collection["inputName"];
}
回答by mipe34
I would create partial views for each option of the dropdown and additional fields. Than controller, that will return such parts of html according to dropdown value:
我会为下拉列表和附加字段的每个选项创建部分视图。比控制器,它将根据下拉值返回 html 的这些部分:
public class FormFieldsController : Controller
{
public ActionResult Index(string dropDownOption)
{
if(dropDownOption == "Option1")
return PartialView("PartialForOption1");
etc.//
}
}
Then just call it with jquery Ajaxand append your current form with result of action, when the value of dropdown changes.
然后只需使用 jquery Ajax调用它,并在 dropdown 的值发生变化时附加您当前的表单和操作结果。
$.ajax("/FormFields/Index",
{
async: false,
data: { dropDownOption: $('#dropDownId').value()},
success: function(data) {
if (callback == null) {
$("#form").append(data);
} else {
callback(data);
}
},
error: function() {
alert('Error');
},
type: 'GET',
timeout: 10000
}
);
回答by Soner
Try this http://mvcdynamicforms.codeplex.com/releases/view/43320it should be helpful
试试这个http://mvcdynamicforms.codeplex.com/releases/view/43320应该会有帮助