如何检查FileUploader在MVC4 asp.net中有文件

时间:2014-07-30 11:52:23

标签: asp.net-mvc asp.net-mvc-4

我正在mvc4中创建一个应用程序。在编辑模式中,我希望用户编辑他/她的详细信息, 用户可以选择从fileuploader中选择更改其个人资料图像。但是如果用户没有在上传器中选择文件,则会发送先前的文件位置。 我将图像路径存储在表中与其他细节相同。 因此,只创建了一个存储过程。 我只有1天的mvc.Started直接在mvc工作,没有老年人的订单。 所以请帮忙

2 个答案:

答案 0 :(得分:0)

以下代码假设您将文件的名称保存在db表中并将文件保存在应用服务器上。

代码如下:

型号:

public string Photo {get;set;}

查看:

<input type='file' id='file'/> 
@Html.HiddenFor(m=>m.Photo)

JS:

// if there is a photo update by user, change the Photo hidden element value
//get the final name of the photo saved in server    
$("#Photo").val(newname);

然后只需发布您的表单。

如果用户没有更改其照片,则之前的值将保留在隐藏元素中并更新到数据库。因此,照片栏中实际上没有任何改变。

我强烈推荐this tutorial for MVC newbie

答案 1 :(得分:0)

使用强类型模型是一种很好的做法。您应该为用户创建一个分离器ViewModel:

模型/ UserEditViewModel

public int Id { get; set; }
public string Name { get; set; }
// Other properties

public HttpPostedFileBase Photo { get; set; }

控制器:

[HttpGet]
public ActionResult Edit(int id)
{
    // Get user from database
    var user = db.Users.Find(id);

    // Map user to UserEditViewModel
    var userVM = new UserEditViewModel
        {
            Id = user.Id;
            Name = user.Name;
            // Other mappings
        }
    return View(userVM);
}

[HttpPost]
public ViewResult Edit(UserEditViewModel model)
{
    if (ModelState.IsValid)
    {
        var existingUser = db.Users.Find(model.Id);

        if (model.Photo != null && model.Photo.ContentLength > 0)
        {
            // Update database and copy image to server
        }

    }
}

查看:

@model YourProject.Models.UserEditViewModel

@using (Html.BeginForm("Edit", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    // Form stuff
    @Html.HiddenFor(m => m.Id)
    @Html.EditorFor(m => m.Name)
    @Html.EditorFor(m => m.Photo) // Creates <input type="file" name="Photo" />

    <input type="submit" value="Save" />
}