上传图像和模型 ASP.NET MVC 4
Upload Image & Model ASP.NET MVC 4
好的,我的照片总是返回 null,
我错过了什么?
我试过这个Uploading/Displaying Images in MVC 4
但我显然希望将图像作为模型的一部分。
型号
public class Client
{
public string Name{ get; set; }
public string ClientId { get; set; }
public HttpPostedFileBase Photo{ get; set; }
}
页
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="form-horizontal" role="form">
<div class="form-group">
<label for="@Model.Name" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input name="ClientId" type="hidden" value="@Model.ClientId" id="ClientId" data-val="true" data-val-required=" required">
<input type="text" id="Name" value="" class="form-control" tabindex="1" placeholder="name" name="Name" required/>
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<label for="@Model.Name" class="col-sm-2 control-label">Image:</label>
<div class="col-sm-10">
@Html.TextBoxFor(m => m.Photo, new { type = "file" })
</div>
</div>
}
控制器
[HttpPost]
[Authorize]
public ActionResult New(ViewModels.Client client)
{
if (client.Photo!= null)
{
var photo= new byte[client.Photo.ContentLength];
client.Photo.InputStream.Read(photo, 0, client.Photo.ContentLength);
}
}
您还没有在表单上设置 enctype
(确保将下面的 Controller
更改为您的控制器名称):
@using (Html.BeginForm("New", "Controller", FormMethod.Post,
new { enctype = "multipart/form-data" }))
好的,我的照片总是返回 null, 我错过了什么?
我试过这个Uploading/Displaying Images in MVC 4
但我显然希望将图像作为模型的一部分。 型号
public class Client
{
public string Name{ get; set; }
public string ClientId { get; set; }
public HttpPostedFileBase Photo{ get; set; }
}
页
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="form-horizontal" role="form">
<div class="form-group">
<label for="@Model.Name" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input name="ClientId" type="hidden" value="@Model.ClientId" id="ClientId" data-val="true" data-val-required=" required">
<input type="text" id="Name" value="" class="form-control" tabindex="1" placeholder="name" name="Name" required/>
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<label for="@Model.Name" class="col-sm-2 control-label">Image:</label>
<div class="col-sm-10">
@Html.TextBoxFor(m => m.Photo, new { type = "file" })
</div>
</div>
}
控制器
[HttpPost]
[Authorize]
public ActionResult New(ViewModels.Client client)
{
if (client.Photo!= null)
{
var photo= new byte[client.Photo.ContentLength];
client.Photo.InputStream.Read(photo, 0, client.Photo.ContentLength);
}
}
您还没有在表单上设置 enctype
(确保将下面的 Controller
更改为您的控制器名称):
@using (Html.BeginForm("New", "Controller", FormMethod.Post,
new { enctype = "multipart/form-data" }))