Adding  new Item to a list of items, inline is a very nice feature you can provide to your user. This posts shows 2 different ways to do this in ASP.NET MVC3 and how Modelbinding handles that.

MVC3 dynamically added form fields model binding

We are going to create a new page where it lists the various Programming Interests a user has.  The user will have an option to add a new Record ( Programming interest) to the list present.

Let’s create 2 ViewModels(ViewModel is a simple POCO class) for our views. Add the below 2 classes to our project.

1
2
3
4
5
6
7
8
9
10
11
12
public class User
{
    public int Id { set; get; }
    public string Name { get; set; }  
    public IList<UserInterest> Interests { get; set; }
}
public class UserInterest
{
    public int Id { set; get; }
    public string InterestText { set; get; }
    public bool IsExperienced { set; get; }
}

Now I am going to create a GET action which returns a User class object with his interests.

1
2
3
4
5
6
7
public ActionResult ClientSideCreation()
{
    var usr = new User();
    usr.Name = "Jon Skeet";
    usr.Interests = GetUserInterests();
    return View(usr);
}

This action is simply creating an object and setting the Name property and Setting the Interests collection. GetUserInterests is a method which returns a list of UserInterest object.

Now to handle the collection Property of our Model, Let’s create an Editor template called  UserInterest.cshtml under HomeEditorTempaltes.

Now we will use Html.EditorFor HTML Helper method to bring this editor template to our main view.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@model MvcApplication2.Models.User
@using(Html.BeginForm())
{
 <h3>Name : @Model.Name</h3>
 <h4>Interests</h4>  
 <div class="divIntersts">
    <table  id="container">
     <tr>
        <th>Name</th><th>Have Experience?</th>
     </tr>
     @Html.EditorFor(x => x.Interests)   
    </table>  
 </div>
 <p><input type="submit" value="Save" /></p>
}

We are done with that. Running the project will show the output like this.

note that this does not have any feature for the user to add the new record to the collection.

Adding Record Inline

I am going to make some changes to our view.

1) Add a button called ” Add new Item ” to our html markup.

<input type="button" id="btnAdd" value="Add New Item" />

2) Add some javascript code to create the form fields when user clicks on the Add New Item button and append that to our table which holds the collection.

1
2
3
4
5
6
7
8
$(function () {
    $("#btnAdd").click(function (e) {
        var itemIndex = $("#container input.iHidden").length;
        e.preventDefault();
        var newItem = $("<tr><td><input id='Interests_" + itemIndex + "__Id' type='hidden' value='' class='iHidden'  name='Interests[" + itemIndex + "].Id' /><input type='text' id='Interests_" + itemIndex + "__InterestText' name='Interests[" + itemIndex + "].InterestText'/></td><td><input type='checkbox' value='true'  id='Interests_" + itemIndex + "__IsExperienced' name='Interests[" + itemIndex + "].IsExperienced' /></tr>");
        $("#container").append(newItem);
    });
});

So the result of running our updated project will be like this. there is a “Add New Item” button and clicking that will add new record to our existing table.

Now When the user posts the form, the MVC Model binding feature will bind the newly added items as well. You can check that by putting a breakpoint in the HttpPost action method.

The trick is to keep the id property value of the html element in this format.

CollectionName_ItemIndex__PropertyName

and name property value in this format

CollectionName[ItemIndex].PropertyName

If your Collection item has many fields, It will be hard to write javascript code for creating the form elements. In that case, You may consider doing it in the server side.

So i will update my javascript code like this.

1
2
3
4
5
6
7
8
9
$(function () {
    $("#btnAdd").click(function (e) {
        var itemIndex = $("#container input.iHidden").length;      
        e.preventDefault();
        $.get("@Url.Action("NewInterestRow", "Home")/"+itemIndex,function(data){
            $("#container").append(data);
        });          
    });
});

You can see that we are not building the html in our client side code here. Instead we are mkaing an ajax call to the NewInterestRow action method and passing the Index of the new item. So we need to create that action method like this.

1
2
3
4
5
public ActionResult NewInterestRow(int id)
{
    var interest = new UserInterest { Id=id};
    return View("Partial/NewInterestRow",interest);
}

It simply creates an object of our UserInterest class and set the Id  property value of it as the values passed to this method (which is the Item Index of the new item to be created) .Then we are passing that object to a partial view called NewInterestRow. So Lets create a new View under Home/Partial called NewInterestRow.cshtml with the below content.

1
2
3
4
5
6
7
8
9
10
11
@model MvcApplication2.Models.UserInterest
@{    Layout = null; }
<tr>
 <td>
  <input type="hidden" id="Interests_@(Model.Id)__Id" class="iHidden"  name='Interests[@Model.Id].Id' />
  <input type='text' id='Interests_@(Model.Id)__InterestText'   name='Interests[@Model.Id].InterestText'/>
 </td>
 <td>
    <input type='checkbox' value='true'  id='Interests_@(Model.Id)__IsExperienced' name='Interests[@Model.Id].IsExperienced' />
 </td>
</tr>

This View also creates the same HTML elements we created at client side previously, with the same name /ID convention we need for the Model binding to work.

Summary : Here we showed 2 ways to add dynamic form fields to an existing collection which gives a nice user experience and how MVC Model binding works for those new elements. The main thing to remember is to keep the format of the name and id property values. Model binding will work for the new elements only if they follow the format.

You can download the sample source code here to see how it works.

Reference: http://www.techiesweb.net/asp-net-mvc3-dynamically-added-form-fields-model-binding/

ASP.NET MVC3 Dynamically added form fields model binding的更多相关文章

  1. [ASP.NET MVC 小牛之路]15 - Model Binding

    Model Binding(模型绑定)是 MVC 框架根据 HTTP 请求数据创建 .NET 对象的一个过程.我们之前所有示例中传递给 Action 方法参数的对象都是在 Model Binding ...

  2. 【ASP.NET MVC 学习笔记】- 16 Model Binding(模型绑定)

    本文参考:http://www.cnblogs.com/willick/p/3424188.html. 1.Model Binding是Http请求和Action方法之间的桥梁,是MVC框架根据Htt ...

  3. asp.net mvc3 的数据验证(一)

    原文:asp.net mvc3 的数据验证(一)      对于web开发人员来说,对用户输入的信息进行验证是一个重要但是繁琐的工作,而且很多开发者都会忽略.asp.net mvc3框架使用的是叫做“ ...

  4. [ASP.NET MVC 小牛之路]16 - Model 验证

    上一篇博文 [ASP.NET MVC 小牛之路]15 - Model Binding 中讲了MVC在Model Binding过程中如何根据用户提交HTTP请求数据创建Model对象.在实际的项目中, ...

  5. ASP.NET MVC3 Model验证总结

    ASP.NET MVC3中的Model是自验证的,这是通过.NET4的System.ComponentModel.DataAnnotations命名空间完成的. 我们要做的只是给Model类的各属性加 ...

  6. ASP.NET MVC3 Model验证总结(转)

    推荐:   ASP.NET MVC的Model元数据与Model模板:预定义模板 http://www.cnblogs.com/artech/archive/2012/05/02/model-meta ...

  7. 转:ASP.NET MVC3 Model验证总结

    http://www.wyjexplorer.cn/Post/2012/8/3/model-validation-in-aspnet-mvc3 ASP.NET MVC3中的Model是自验证的,这是通 ...

  8. ASP.NET MVC3 Model验证总结 @Html.ValidationSummary(true)

    http://www.wyjexplorer.cn/Post/2012/8/3/model-validation-in-aspnet-mvc3 ASP.NET MVC3中的Model是自验证的,这是通 ...

  9. ASP.NET MVC3中Model验证

    原文:ASP.NET MVC3中Model验证 概述 上节我们学习了Model的数据在界面之间的传递,但是很多时候,我们在数据传递的时候为了确保数据的有效性,不得不给Model的相关属性做基本的数据验 ...

随机推荐

  1. EF Code First教程-01 创建一个简单的Code First程序

    1 从nuget中搜索并添加EF 2 在app.config或web.config中添加数据库连接 <connectionStrings> <add name="conns ...

  2. Java 静态类 static

    静态的方法是非虚方法(Java中的非虚方法有private,final,static,构造器,非虚方法无需根据具体的对象遍历方法区的方法表,决定调用关系) 也就是说,对于静态类型方法的调用,是其声明类 ...

  3. 第十篇 Integration Services:高级事件行为

    本篇文章是Integration Services系列的第十篇,详细内容请参考原文. 简介在前一篇, we introduced fault tolerance by examining method ...

  4. [PCL]2 点云法向量计算NormalEstimation

    从GitHub的代码版本库下载源代码https://github.com/PointCloudLibrary/pcl,用CMake生成VS项目,查看PCL的源码位于pcl_features项目下 1. ...

  5. 分享书籍[writing idiomatic python ebook]

    你是不是总是觉得学了python好久,蓦然回首,总是感觉写的代码不是那么有pythonic的味道.看看别人的代码(django,webpy),再看看自己的代码,觉得就是一java-python的混合体 ...

  6. set方法内存分析

    // //  main.m //  04-set方法的内存管理分析 // //  Created by apple on 14-3-17. // // #import <Foundation/F ...

  7. sql server常见服务

    根据您决定安装的组件,SQL Server 安装程序将安装以下服务: SQL Server Database Services - 用于 SQL Server 关系数据库引擎的服务. 可执行文件为 & ...

  8. zabbix服务器监控suse系统教程

    zabbix服务器监控suse系统教程 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 花了近一个星期才学会了如何监控window和linux主机的基本信息以及报价情况(我已经把笔记 ...

  9. 使用visual studio 2012 编译opencv2.4.9

    最近,由于需要从opencv源码部分对opencv中的某个函数进行修改,以提升算法的速度,因此一直在尝试使用vs2012来编译opencv.期间不乏多次的失败.今天通过实验发现了自己编译的opencv ...

  10. [转]Chrome 控制台console的用法

    Chrome 控制台console的用法 下面我们来看看console里面具体提供了哪些方法可以供我们平时调试时使用. 目前控制台方法和属性有: ["$$", "$x&q ...