首页 > 技术文章 > MVCForm表单图片添加

htbmvc 2017-11-22 19:28 原文

///视图

@using (Html.BeginForm("addinsert", "student", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
<table class="table table-bordered " style="height:450px">
<tr>
<td colspan="2"><h2 style="color:red">添加功能</h2></td>
</tr>
<tr>
<td>姓名</td>
<td>@Html.TextBoxFor(T => T.name, new { @class = "form-control" })</td>
</tr>
<tr>
<td>头像</td>
<td><input name="img" type="file" class="form-control" /></td>
</tr>
<tr>
<td>性别</td>
<td>
@Html.RadioButtonFor(T => T.sex, true)男
@Html.RadioButtonFor(T => T.sex, false)女
</td>
</tr>
<tr>
<td>年龄</td>
<td>@Html.TextBoxFor(T => T.age, new { @class = "form-control" })</td>
</tr>
<tr>
<td>国籍</td>
<td>@Html.DropDownListFor(T => T.homeid, ViewBag.list as SelectList, new { @class = "form-control" })</td>
</tr>
<tr>
<td>爱好</td>
<td>
@foreach (var item in ViewBag.che as List<shizhan2.Models.checklist>)
{
<input id="Checkbox1" name="aihao" type="checkbox" value="@item.name" />@item.name
}
</td>
</tr>
<tr>
<td>时间</td>
<td>@Html.TextBoxFor(T => T.shijian, new { @class = "form-control" })</td>
</tr>
<tr>
<td></td>
<td><input id="Button1" type="submit" value="添加" class="btn btn-primary" /></td>
</tr>

</table>
}

///控制器

/// <summary>
/// 添加GET请求
/// </summary>
/// <returns></returns>
public ActionResult addinsert()
{
//获取下拉列表的值
var result = new BLL.homebll().getdatatble();
SelectList list = new SelectList(result, "homeid", "homename");
ViewBag.list = list;

var checkedlist = new List<checklist>() {
new checklist(){ id =1, name ="打球"},
new checklist(){ id =2, name ="唱歌"},
new checklist (){ id=3, name="唱戏"},
new checklist(){ id =4, name="敲代码"}
};
ViewBag.che = checkedlist;
return View();
}
[HttpPost]
public ActionResult addinsert(studentM m)
{
//获取图片的字段
var file = Request.Files["img"];
//获取图片的路径
var filepath = "/Content/img/" + file.FileName;
//转化为虚拟路径
file.SaveAs(Server.MapPath(filepath));
//接受复选框的值
var bql = Request.Form["aihao"];
//转化三层的数据
var model = new studentmodel
{
id = m.id,
img = filepath,
shijian = m.shijian,
aihao = bql,
homeid = m.homeid,
age = m.age,
sex = m.sex,
name = m.name
};
//接受bll层的方法
var result = new BLL.studentbll().addinsert(model);


if (result > 0)
{
return Content("ok");
}
else
{
return Content("<script>alert('添加失败');</script>");
}
}

推荐阅读