【问题标题】:How to set input file in Razor 3 MVC 5如何在 Razor 3 MVC 5 中设置输入文件
【发布时间】:2014-06-04 21:26:01
【问题描述】:

我在 MVC 5 和 Razor 5 中有这样的页面代码:

<input type="file" name="file" />

<img src=@Url.Content(Model.ImagePath)" alt="Image"/>

当我创建新项目并通过输入类型文件添加图像时,它可以正常工作。但是我在 Edit.cshtml 中有相同的代码,我想从 Model 设置输入类型文件,并且 id 不起作用。我无法设置这个输入文件。

谢谢

【问题讨论】:

    标签: c# asp.net-mvc-5 razor-2


    【解决方案1】:

    您需要在模型中创建属性:

    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" />
    }
    

    在控制器中:

    [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;
            }
    
        }
    }
    

    【讨论】:

    • 谢谢,model.ImageUpload 为空,我尝试解决这个问题
    • 我添加了 [NotMapped] 表单属性 ImageUpload
    • HttpPostedFileBase 是抽象类,我无法创建此类的实例
    • 是的,但是我写了 addind 工作,我有问题从模型设置输入文件
    猜你喜欢
    • 2013-11-25
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2011-06-25
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多