【问题标题】:Upload image to SQL server using view, view model, and controller使用视图、视图模型和控制器将图像上传到 SQL Server
【发布时间】:2014-12-14 10:31:19
【问题描述】:

我在 VS 2013 中,一般来说对 ASP.NET MVC 完全陌生。我一直在尝试这样做,但没有运气。让用户完成带有图像上传的表单,并将该表单与图像写入数据库。我知道最好将路径写入数据库并将图像存储在应用程序的内容文件夹中,但我不知道该怎么做。谁能给我一个起点?

我还有一个 ClientUtility.cs 用于填充下拉列表,但我认为现在不需要它。

目前 db 中 image ref 的数据类型为VARCHAR(255)

Controller:

    private TpsEntities db = new TpsEntities();
    [HttpPost]
    public ActionResult SaveStaffDetails(RegisterStaffViewModel model)
    {

        var staff = new staffTable()
        {
            staffFirstName = model.FirstName,
            staffLastName = model.LastName,
            staffTitle = model.SelectedTitle,
            staffAddress = model.Address,
            staffCity = model.City,
            staffState = model.SelectedState,
            staffZip = model.ZipCode,
            staffExperience = model.SelectedExperience,
            staffEducation = model.SelectedEducation,
            desiredSalary = model.SelectedSalary,
            staffProfession = model.SelectedProfession,
            staffAvailibity = model.SelectedAvailability,
            staffEmail = model.EmailAddress,
            staffPhoneNum = model.PhoneNumber,
            staffPhoto = null,
            userID = model.UserId
        };

        using (var db = new TpsEntities())
        {
            db.staffTables.Add(staff);
            db.SaveChanges();
        }

        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = userManager.FindById(model.UserId);

        userManager.AddToRole(model.UserId, "Staff");

        ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaim(new Claim(ClaimTypes.Role, "Staff"));


        var AuthenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;

        AuthenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = false}, identity);

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

ViewModel:

public class RegisterStaffViewModel
{
    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }


    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Address")]
    public string Address { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Title { get; set; }
    [Required]
    [Display(Name = "Title")]
    public string SelectedTitle { get; set; }

    [Required]
    [Display(Name = "City")]
    public string City { get; set; }

    public System.Web.UI.WebControls.ListItemCollection States { get; set; }
    [Required]
    [Display(Name = "State")]
    public string SelectedState { get; set; }

    [Required]
    [Display(Name = "Zip Code")]
    public double? ZipCode { get; set; }

    [Required]
    [Phone]
    [Display(Name = "Phone Number")]
    public string PhoneNumber { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Experience { get; set; }
    [Required]
    [Display(Name = "Experience")]
    public string SelectedExperience { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Education { get; set; }
    [Required]
    [Display(Name = "Education")]
    public string SelectedEducation { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Salary { get; set; }
    [Required]
    [Display(Name = "Salary")]
    public string SelectedSalary { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Profession { get; set; }
    [Required]
    [Display(Name = "Profession")]
    public string SelectedProfession { get; set; }

    public System.Web.UI.WebControls.ListItemCollection Availability { get; set; }
    [Required]
    [Display(Name = "Availability")]
    public string SelectedAvailability { get; set; }

    public string UserId { get; set; }
}

View:

@*Start of Registration Form for Staff*@

@using (Html.BeginForm("SaveStaffDetails", "Staff", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
            @Html.AntiForgeryToken()
            @Html.HiddenFor(m => m.UserId)
            <fieldset>

                <!-- Form Name -->
                <legend>Register New Staff</legend>

                @*First Name*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control input-md", @placeholder = "First Name" })
                    </div>
                </div>

                @*Last Name*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control input-md", @placeholder = "Last Name" })
                    </div>
                </div>

                @*Person Title*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="title">Title</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedTitle, new SelectList(Model.Title, "Text", "Value"))
                    </div>
                </div>


                @*Address Line*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.Address, new { @class = "form-control input-md", @placeholder = "Address" })
                    </div>
                </div>

                @*City*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.City, new { @class = "form-control input-md", @placeholder = "City" })
                    </div>
                </div>

                @*State*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="state">State</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedState, new SelectList(Model.States, "Text", "Value"))
                    </div>
                </div>

                @*Zip Code*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control input-md", @placeholder = "Zip Code" })
                    </div>
                </div>

                @*Phone Number*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "form-control input-md", @placeholder = "Phone Number" })
                    </div>
                </div>

                @*Email Address*@
                <div class="form-group">
                    <div class="col-md-6">
                        @Html.TextBoxFor(m => m.EmailAddress, new { @class = "form-control input-md", @placeholder = "Email Address" })
                    </div>
                </div>

                @*Experience*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="experience">Experience</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedExperience, new SelectList(Model.Experience, "Text", "Value"))
                    </div>
                </div>

                @*Education*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="education">Education</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedEducation, new SelectList(Model.Education, "Text", "Value"))
                    </div>
                </div>

                @*Desired Salary*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="salary">Desired Salary</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedSalary, new SelectList(Model.Salary, "Text", "Value"))
                    </div>
                </div>

                @*Profession*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="profession">Profession</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedProfession, new SelectList(Model.Profession, "Text", "Value"))
                    </div>
                </div>

                @*Availability*@
                <div class="form-group">
                    <label class="col-md-6 control-label" for="availability">Availability</label>
                    <div class="col-md-6">
                        @Html.DropDownListFor(m => m.SelectedAvailability, new SelectList(Model.Availability, "Text", "Value"))
                    </div>
                </div>

                <!-- INSERT IMAGE UPLOAD HERE -->
            </fieldset>

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

【问题讨论】:

    标签: c# sql-server model-view-controller asp.net-mvc-5 image-uploading


    【解决方案1】:

    按照以下代码编辑您的控制器。我假设staffPhoto正在拍摄图片路径。

    public ActionResult SaveStaffDetails(RegisterStaffViewModel model,HttpPostedFileBase image)
    {
        if (Request.Files.Count > 0) {
            string FileName = Guid.NewGuid().ToString().Replace("-", "");
            string Path = System.IO.Path.GetExtension(Request.Files[0].FileName);
            string FullPath = "~/Images/StaffPhotos/" + FileName + Path;
            Request.Files[0].SaveAs(Server.MapPath(FullPath));
            staffPhoto = FileName + Path;
        }
    }
    

    在您看来,您需要一个文件发布输入

    <input type="file" class="filestyle" name="image" data-classbutton="btn btn-primary" data-input="false">
    

    【讨论】:

    • 我在上面的控制器中添加了您指示的内容 var staff = new staffTable()。它不需要。当前上下文中不存在staffPhoto。
    • 它不会保存,因为您的模型中没有任何包含 photopath 的变量。包括公共字符串 somethingPath{get; set;}在您的数据库中,必须有一列属于 photopaths。
    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多