C# 如何在Razor3MVC5中设置输入文件
我在MVC 5和Razor 5页面中有如下代码:C# 如何在Razor3MVC5中设置输入文件,c#,asp.net-mvc-5,razor-2,C#,Asp.net Mvc 5,Razor 2,我在MVC 5和Razor 5页面中有如下代码: <input type="file" name="file" /> <img src=@Url.Content(Model.ImagePath)" alt="Image"/> 当我创建新项目并按输入类型文件添加图像时,它工作正常。但我在Edit.cshtml中有相同的代码,我想从Model和id中设置输入类型文件,但它不起作用。我无法设置此输入文件 谢谢您需要在模型中创建属性: public class ViewM
<input type="file" name="file" />
<img src=@Url.Content(Model.ImagePath)" alt="Image"/>
当我创建新项目并按输入类型文件添加图像时,它工作正常。但我在Edit.cshtml中有相同的代码,我想从Model和id中设置输入类型文件,但它不起作用。我无法设置此输入文件
谢谢您需要在模型中创建属性:
public class ViewModel
{
public string ImagePath{ get; set; }
.....
}
在编辑视图中:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
<label for="ImageUpload">Filename:</label>
<input type="file" name="ImageUpload" id="ImageUpload" />
}
谢谢,model.ImageUpload为空,我试图解决这个问题,我添加了[NotMapped]表单属性ImageUploadHttpPostedFileBase是抽象类,我无法创建这个类的实例是的,但我写了addind可以工作,我无法从模型设置输入文件
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
var file = Request.Files["ImageUpload"];
if (file != null && file.ContentLength > 0){
var uploadDir = "~/uploads"
var imagePath = Path.Combine(Server.MapPath(uploadDir), file.FileName);
var imageUrl = Path.Combine(uploadDir, file.FileName);
file.SaveAs(imagePath);
model.ImagePath= imageUrl;
}
}
}