Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在asp.net mvc中用用户对象将图像传递到数据库_C#_Asp.net Mvc - Fatal编程技术网

C# 如何在asp.net mvc中用用户对象将图像传递到数据库

C# 如何在asp.net mvc中用用户对象将图像传递到数据库,c#,asp.net-mvc,C#,Asp.net Mvc,型号为用户: public class Users { [Key] public int UserId { get; set; } [Required] public string Firstname { get; set; } public string Lastname { get; set; } [Required] public string Username { g

型号为用户:

 public class Users
    {
        [Key]
        public int UserId { get; set; }
        [Required]
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        [Required]
        public string Username { get; set; }
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
        public string UserImage { get; set; }
    }
在用户控制器中创建ActionMethod:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "UserId,Firstname,Lastname,Username,Password,UserImage")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }
最后,创建视图如下所示:

@model WebApplication2.Models.Users

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Users</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Firstname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Firstname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Firstname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Lastname, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Lastname, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Lastname, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserImage, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="UserImage" value="" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
@model WebApplication2.Models.Users
@{
ViewBag.Title=“创建”;
}
创造
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
使用者

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @LabelFor(model=>model.Firstname,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Firstname,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Firstname,“,new{@class=“text danger”}) @LabelFor(model=>model.Lastname,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Lastname,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Lastname,“,new{@class=“text danger”}) @LabelFor(model=>model.Username,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Username,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Username,“,new{@class=“text danger”}) @LabelFor(model=>model.Password,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Password,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Password,“,new{@class=“text danger”}) @LabelFor(model=>model.UserImage,htmlAttributes:new{@class=“controllabel col-md-2”}) } @ActionLink(“返回列表”、“索引”) @节脚本{ @Scripts.Render(“~/bundles/jqueryval”) }

因此,请帮助我该怎么做?如何使用此用户对象将图像名称传递到数据库?我已经尝试了很多次,但都失败了。

不要使用EF中的实体类在视图和操作方法之间传输数据。您应该创建一个视图模型。您可以为用户映像添加类型为
HttpPostedFileBase

public class CreateUserVm
{       
    public int UserId { get; set; }
    [Required]
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    public HttpPostedFileBase UserImage { get; set; }
}
现在,在获取中,确保发送此CreateUserVm类的对象

public ActionResult Create()
{
  return View(new CreateUserVm());
}
您的创建视图将强类型化到此视图模型

@model YourNameSpaceHere.CreateUserVm
@using (Html.BeginForm("Create", "Home", FormMethod.Post, 
                                 new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(false)
    <div class="form-group">
        @Html.LabelFor(model => model.Name,  new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Name, new  { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Name, 
                                      "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.UserImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
          <input type="file" name="UserImage" />
        </div>
    </div>
    <input type="submit" />
}

好的,你有几件事要做才能让这一切顺利进行。首先,您需要更改视图中的表单类型,以向服务器指示文件即将到达:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //Form Stuff here
}
然后,在控制器端,您需要通过添加
HttpPostedFileBase
类型的参数
UserImage
,告诉服务器在post请求中需要一个文件:

public ActionResul Upload([Bind(Include = "UserId,Firstname,Lastname,Username,Password")] Users users, HttpPostedFileBase UserImage)
{
    //Controller Logic
}
现在,您的视图正在发送图像,控制器正在接受它…现在我们需要解决在数据库中存储图像的概念。您可以通过将上传的图像(现在存储在
UserImage
变量中)转换为字节数组(我的帖子中没有显示此过程)并将
Users
模型中的属性从以下位置更改为:

public string UserImage { get; set; }
对下列事项:

public byte[] UserImage { get; set; }
但是,我建议您不要这样做,因为有几个原因……相反,我建议您执行以下操作:

public byte[] UserImage { get; set; }
  • 使用唯一的名称将图像保存在服务器上的文件夹中(例如`\App\u Data\UserProfilePhotos\Bob\u Smith\u Profile\u Photo.jpg)
  • 将数据库的UserImage属性中的照片名称另存为字符串
  • 在用户控制器(例如
    yoursite.com/Users/ProfileImage/{UserID}
    中创建一个端点(操作方法),用于检索图像
  • 在用户配置文件视图(或图像将显示的任何位置)中,动态创建图像标记,如
    用户图像
    ,该标记将加载正确的用户图像
  • 我不会为您概述上述工作流程的每个步骤,但这通常就是您所描述的用例的处理方式