Hinzufügen eines Bild-Datenbank in ASP.NET MVC 5

Ich versuche ein Bild hinzufügen, um eine Datenbank-Tabelle mithilfe von ASP.NET MVC mit Entity Framework.

Habe ich eine migration von bestehenden ASP.NET MVC-Tabelle mit dem Namen 'AspNetUsers" und fügte einige neue Spalten in der it.

Einer der Spalten ProfilePicture, und es ist byte[] geben.

Wenn ich versuche mich als neuer Benutzer registrieren ich gehe davon aus, dass Benutzer bieten, es ist Profilbild neben anderen Daten auch.

Hier ist ApplicationUser Klasse mit neu hinzugefügten Eigenschaften:

public class ApplicationUsers : IdentityUser
    {
        public string Name { get; set; }
        public string LastName { get; set; }
        public string City { get; set; }
        public string DateOfBirth { get; set; }
        public byte[] ProfilePicture { get; set; }

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUsers> manager)
        {
            //Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            //Add custom user claims here
            return userIdentity;
        }
    }

Bekommen Sie das Bild in Tabelle, ich bin mit der wrapper-Klasse namens ExtendedIdentityModels. Diese Klasse erbt von RegisterViewModel Klasse und es hat nur eine Eigenschaft UserProfilePicture, Art der HttpPostedFileBase, für immer das Bild von user-Seite.

 public class ExtendedIdentityModels : RegisterViewModel
    {
        public HttpPostedFileBase UserProfilePicture { get; set; }
    }

Habe ich geändert Register-Methode im controller hinzufügen, um diesen neue Eigenschaften zu Datenbank:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(ExtendedIdentityModels model)
    {
        if (ModelState.IsValid)
        {
            if (model.UserProfilePicture != null)
            {
                 if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
                 {
                      ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return View();
                 }
                 if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
                 {
                     ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                 }
             }
             byte[] data = new byte[model.UserProfilePicture.ContentLength];
             model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);
             var user = new ApplicationUsers() { UserName = model.Email, Email = model.Email, Name = model.Name, LastName = model.LastName, City = model.City, DateOfBirth = model.DateOfBirth.ToString(), ProfilePicture = data };
             var result = await UserManager.CreateAsync(user, model.Password);
             if (result.Succeeded)
             {
                 await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                      return RedirectToAction("Index", "Home");
             }
                        AddErrors(result);

                }
                //If we got this far, something failed, redisplay form
                return View(model);
}

Für die Interaktion mit dem Benutzer verwende ich folgende Ansicht, auf der Unterseite dieser code ist ein Teil für das hinzufügen ProfilePicture.

@model StudentBookApp.Models.ExtendedIdentityModels
@{
    ViewBag.Title = "Register";
}

@*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>*@

<link href="~/Content/datepicker.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<h2>@ViewBag.Title.</h2>

@using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.LastName, new { @class = "form-control " })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.City, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.DateOfBirth, new { @class = "datepicker form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ProfilePicture, new { @class = "col-md-2 control-label"})
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserProfilePicture, new {type = "file"})
            @Html.ValidationMessage("CustomMessage")
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Register" />
        </div>
    </div>
}

<script type="text/javascript">

    $(function () {
        $('.datepicker').datepicker();
    })
</script>

Fast alles gut geht, aber für das Modell.UserProfilePicture bekomme ich null Wert. Aus irgendeinem Grund wird es nicht passieren, aus Sicht. Was mache ich falsch? Ich habe schon stecken für Stunden zu versuchen, um mögliche Fehler, aber auch kein Erfolg. Diese Art von "Mechanismus" für einfügen, Bild in Tabelle verwenden, um gut in MVC 4... Hat jemand erkannt, was mir fehlt und was falsch ist in dieser Art von Ansatz?

  • Das ist einige tolle C#, MVC und Razor. Ich wünschte, ich wüsste, wie man Sie alle, wie Sie es tun.
InformationsquelleAutor nemo_87 | 2015-01-13
Schreibe einen Kommentar