我希望用户能够上传图像并将其存储在服务器上以供以后参考。
这是一些代码:
SliderController.cs:
public ActionResult Create()
{
return View(new SliderImageViewModel());
}
[HttpPost]
public ActionResult Create(SliderImageViewModel sliderImage)
{
if (ModelState.IsValid)
{
var slider = new SliderImage();
var lastSortOrder =
Context.SliderImages.Select(p => p.SortOrder).DefaultIfEmpty(0).Max();
slider.SortOrder = lastSortOrder + 1;
//TODO: upload image to server and get physical path (GUID)
//slider.ImageUrl = physical path
Context.SliderImages.Add(slider);
Context.SaveChanges();
return RedirectToIndex();
}
else
return View(sliderImage);
}
public class SliderImageViewModel
{
[RequiredValue]
public HttpPostedFileBase Image { get; set; }
private string _Content;
public string Content
{
get
{
if (string.IsNullOrWhiteSpace(_Content))
return null;
else
return _Content;
}
set { _Content = value; }
}
}
创建.cshtml:
@using (Html.BeginForm("Create", "Slider", FormMethod.Post))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Page</legend>
<div class="editor-label">
@Html.Label("Content")
</div>
<div class="editor-field">
@Html.TextBox("content")
</div>
<div class="editor-label">
@Html.Label("Image")
</div>
<div class="editor-field">
@Html.TextBox("image", null, new { type = "file", accept = "image/*" })
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
当我提交表单时,参数中的Image
属性sliderImage
为空(Content
有效),我应该如何解决这个问题?