我正在使用我的MVC应用程序,我想在我的视图中上传一个很好的文件。到目前为止,我的控制器是这样的:
&
在我看来,我想要上传文件,以便我可以在public ActionResult PickGroupForHomework(PickGroupForHomeworkViewModel model)
{
ClassDeclarationsDBEntities2 entities = new ClassDeclarationsDBEntities2();
model.groups = entities.Groups.ToList();
model.users = entities.Users.ToList();
if(ModelState.IsValid)
{
}
else
{
model.subject_id = model.subject_id;
model.groups = model.groups;
model.users = model.users;
return View(model);
}
return View(model);
}
中检索它,然后将其作为文件上传到服务器上。我该怎么办?
修改
所以我将此添加到我的观点中:
if(ModelState.IsValid
但是如何将所选文件传递给模型中定义的<div class="form-group">
@Html.LabelFor(m => m.file, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
<input type="file" name="file" />
</div>
</div>
?
的 EDIT2:
我现在的观点是这样的:
HttpPostedFileBase file
显然这@model ClassDeclarationsThsesis.Models.PickGroupForHomeworkViewModel
@{
ViewBag.Title = "Pick Group For Homework";
}
<h2>Setting homework</h2>
@foreach (var user in Model.users)
{
if (user.email.Replace(" ", String.Empty) == HttpContext.Current.User.Identity.Name)
{
if (user.user_type.Replace(" ", String.Empty) == 2.ToString()|| user.user_type.Replace(" ", String.Empty) == 3.ToString())
{
using (Html.BeginForm("PickGroupForHomework", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<hr />
<div class="form-group">
@Html.LabelFor(m => m.deadline, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.deadline, new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.file, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
<div class="editor-field">
@Html.EditorFor(m=>m.file, new { @class="col-md-2 control-label"})
@Html.ValidationMessageFor(m=>m.file)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Submit" />
</div>
</div>
}
}
if (user.user_type.Replace(" ", String.Empty) == 1.ToString() )
{
<p>You do not have enough permissions to enter this page. Contact the administrator.</p>
}
}
}
会产生这样的观点:
答案 0 :(得分:1)
要从表单上传文件,表单应该有 enctype属性,其值设置为&#34; multipart / form-data&#34;
使用此代码
@using (Html.BeginForm("PickGroupForHomework", "Account", FormMethod.Post,
new { @class = "form-horizontal",enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" />
}
这将生成form
标记的html标记,enctype
属性值设置为&#34; multipart / form-data&#34;