码迷,mamicode.com
首页 > Web开发 > 详细

使用Jquery动态加入对象的集合属性,提交集合属性到表单

时间:2015-03-31 14:20:05      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

1、设置模型,引入构造函数,初始化集合

public class Person
{
public Person() //引入构造函数,初始化集合.如果未设置构造函数,集合会出现错误。
{
Skills = new HashSet<string>();
BirthDate = DateTime.Now.AddDays(-20);
}

public int PersonId { get; set; }

[Required]
public string FirstName { get; set; }

[Required]
public string LastName { get; set; }

[Required]
public DateTime BirthDate { get; set; }

[Required]
[UIHint("BooleanButtonLabel")] //给指定字段指定显示模板。用于html模板辅助方法,比如html.DisplayForModel
public bool LikesMusic { get; set; }

[Required]
[EmailAddress]
public string EmailAddress { get; set; }


public ICollection<string> Skills { get; set; }
}

 

2、设置控制器方法

public ActionResult Create()
{
var person = new Person();
return View(person);
}

[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
_people.Add(person);
return RedirectToAction("Index");
}

return View(person);

}

3、使用基架生成强类型视图

@model BootstrapMVC30Days.Models.Person

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

<div class="form-group">
@Html.LabelFor(model => model.LikesMusic, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.LikesMusic)
@Html.ValidationMessageFor(model => model.LikesMusic, "", new { @class = "text-danger" })
</div>
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Skills, htmlAttributes: new { @class ="control-label col-md-2"})
<div class="col-md-10">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" id="add-skill" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
<input type="text" id="skill" class="form-control" placeholder="输入然后点击 + 加入" />

</div>
</div>
</div>

<div id="skills-wrapper"></div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<ul id="skills-list" class="list-group"></ul>
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>

4、在页面底部引入脚本   。虽然我们加入了多个同名(name相同)的隐藏表单,但模型绑定会将它作为集合来处理。

@section Scripts {
<script>
$(function () {
$("#add-skill").click(function () {
//取得文本框的值
var skill = $("#skill").val();

//加入隐藏输入到表单
$("#skills-wrapper").append($("<input type=‘hidden‘ name =‘Skills‘ value=‘" + skill + "‘ />"));

//加入输入到列表框用于显示
$("#skills-list").append($("<li class=‘list-group-item‘> " + skill + "</li>"));

//重置表单,文本框获得焦点
$("#skill").val("").focus;
});

});
</script>
@Scripts.Render("~/bundles/jqueryval")
}

使用Jquery动态加入对象的集合属性,提交集合属性到表单

标签:

原文地址:http://www.cnblogs.com/liuyuanhao/p/4380538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!