I am maing my MVC application and I would like to make a nice file upload in my view. My controller is like this so far:
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);
}
And in my view I would like to make a file upload so that I can retrieve it in if(ModelState.IsValid
and then upload it as a file on server. How do I do this?
EDIT:
So I added this to my view:
<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>
But how do I pass the chosen file to the HttpPostedFileBase file
defined in model?
EDIT2:
My view now if like this:
@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>
}
}
}