将图像保存到MVC 4中的数据库

时间:2014-04-23 14:14:05

标签: asp.net-mvc-4

我正在尝试使用mvc 4将图像文件名和位置保存到数据库中。有人能看到我出错的地方吗?我只是mvc的新手,并为客户构建这个。我在这行“if(Request.Files.Count> 0)”上设置了一个断点,但它会跳过它并进入我的else语句。

public ActionResult Create2(FestivalVM model)
    {
        if (ModelState.IsValid != true)
        {
            if (model.SelectedFestivalType != -1)
            {
                //db.save stuff from create.
                Festival Newfestival = new Festival();
                Newfestival.EndDate = model.endDate.Date;
                Newfestival.FestivalCounty = db.Counties.Where(p => p.ID == model.SelectedCounty).Single();
                Newfestival.FestivalName = model.FestivalName;
                Newfestival.Description = model.sDescription;
                Newfestival.FType = db.FestivalTypes.Where(p => p.ID == model.SelectedFestivalType).Single();
                Newfestival.StartDate = model.startDate.Date;
                Newfestival.Location = model.Location;
                Newfestival.FestivalTown = db.Towns.Where(p => p.ID == model.SelectedTown).Single();
                Newfestival.UserID = WebSecurity.CurrentUserId;

                if (Request.Files.Count > 0)
                {
                    string fileName = Guid.NewGuid().ToString();
                    string serverPath = Server.MapPath("~\\Content\\FestivalLogo");
                    Bitmap newImage = new Bitmap(Request.Files[0].InputStream);
                    newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    model.festivalLogo = "Content/FestivalLogo/" + fileName + ".jpg";

                    db.Festivals.Add(Newfestival);
                    db.SaveChanges();
                    return RedirectToAction("Details", new {id = Newfestival.FestivalId});
                }
                else
                {
                    db.Festivals.Add(Newfestival);
                    db.SaveChanges();
                    return RedirectToAction("Details", new { id = Newfestival.FestivalId });   
                }
            }
            ModelState.AddModelError("", "No Festival Type Picked");
        }
        model.County = db.Counties.ToDictionary(p => p.ID, q => q.Name);
        model.FestivalType = db.FestivalTypes.ToDictionary(p => p.ID, q => q.FType);
        model.FestivalType.Add(-1, "--- Add New Festival Type ---");
        model.Towns = db.Towns.ToDictionary(p => p.ID, q => q.Name);
        model.startDate = DateTime.Now;
        model.endDate = DateTime.Now;
        return View(model);
    }

查看 - 在此编辑

@model MyFestival.Models.FestivalVM
@{
ViewBag.Title = "Add a Festival";
Layout = "~/Views/Shared/Festival.cshtml";
}

<h2>Create Your Festival</h2>
<br />
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
    <ol class="breadcrumb">
        <li><a href="~/Festival/">Home</a></li>
        <li class="active">Creating a Festival</li>
    </ol>

    <hr />
    @Html.ValidationSummary(true, null, new{@class="alert alert-danger"})

    <div class="form-group">
        @Html.LabelFor(model => model.FestivalName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
                @Html.TextBoxFor(model => model.FestivalName, new { @class = "form-control", @style = "width:210px" })
            </div>
            @Html.ValidationMessageFor(model => model.FestivalName, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.startDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                @Html.TextBoxFor(model => model.startDate, new { @class = "form-control datepicker", @style = "width:250px" })
            </div>
            @Html.ValidationMessageFor(model => model.startDate, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.endDate, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
                @Html.TextBoxFor(model => model.endDate, new { @class = "form-control datepicker", @style = "width:250px" })
            </div>
            <!--<input class="form-control datepicker" style="width:250px" name="endDate" placeholder="Please pick date..."/>-->
            @Html.ValidationMessageFor(model => model.endDate, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Towns, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
                @Html.DropDownListFor(p => p.SelectedTown, Model.Towns.Select(p => new SelectListItem()
            {
                Text = p.Value.ToString(),
                Value = p.Key.ToString(),
                Selected = false
            }),
                new
                {
                    @class = "form-control",
                    @style = "width:210px",
                    placeholder = "---- Select a Town ----"
                })
            </div>
            @Html.ValidationMessageFor(model => model.Towns, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.County, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
                @Html.DropDownListFor(p => p.SelectedCounty, Model.County.Select(p => new SelectListItem()
            {
                Text = p.Value.ToString(),
                Value = p.Key.ToString(),
                Selected = false
            }),
                new
                {
                    @class = "form-control",
                    @style = "width:210px"
                })
            </div>
            @Html.ValidationMessageFor(model => model.County, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FestivalType, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-tag"></i></span>
                @Html.DropDownListFor(p => p.SelectedFestivalType, Model.FestivalType.Select(p => new SelectListItem()
                {
                    Text = p.Value.ToString(),
                    Value = p.Key.ToString(),
                    Selected = false
                }),
                    new
                    {
                        @class = "form-control",
                        @style = "width:210px;",
                        @onchange = "checkaddnew();"
                    })
            </div>
            @Html.ValidationMessageFor(model => model.FestivalType, null, new { @style = "color:red;" })

        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.sDescription, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
                @Html.TextAreaFor(model => model.sDescription, new { @class = "form-control", @style = "width:210px;" })
            </div>
            @Html.ValidationMessageFor(model => model.sDescription, null, new { @style = "color:red;" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-info-sign"></i></span>
                @Html.TextAreaFor(model => model.Location, new { @class = "form-control", @style = "width:210px" })
            </div>
            @Html.ValidationMessageFor(model => model.Location, null, new { @style = "color:red;" })
        </div>
    </div>

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

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

            @Html.ActionLink("Back to List", "Index", null, new { @class = "btn btn-danger" })

        </div>
    </div>
</div>
}

@Html.Partial("CreateFestivalType", new MyFestival.Models.FestivalTypeVM())

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")

<script>
    $(document).ready(function () {
        $('#SelectedFestivalType').change(function () {
            if ($(this).find(":selected").val() == -1) {
                $('#myModal').modal('show');
            }
        });
    });
</script>
<script type="text/javascript">
    function ajaxResponse(data) {
        alert("This Worked and the Data ID is: " + data.FestivalTypeID);
        var newOption = "<option value='" + data.FestivalTypeID + "'>" + data.Name + "</option>";
        $('#SelectedFestivalType').append(newOption);
        $('#myModal').modal('hide');

        $("#SelectedFestivalType option[value='" + data.FestivalTypeID + "']").attr("selected", "selected");
    }

    ;
</script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#startDate").datepicker("setDate", '+1', { dateFormat: "dd/mm/yy" }).on('changeDate', function (ev) {
            $(this).blur();
            $(this).datepicker('hide');
        });
    });
</script>

<script type="text/javascript">
    $(document).ready(function () {
        $("#endDate").datepicker("setDate", '+2', { dateFormat: "dd/mm/yy" }).on('changeDate', function (ev) {
            $(this).blur();
            $(this).datepicker('hide');
        });
    });
</script>

模型

public class Festival
{
    [Key]
    public int FestivalId { get; set; }

    [Required]
    [Display(Name = "Festival Name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string FestivalName { get; set; }

    [Required]
    [Display(Name = "Start Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    [Required]
    [Display(Name = "End Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime EndDate { get; set; }

    [Display(Name = "Festival Location")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public DbGeography Location { get; set; }

    [Required]
    [Display(Name = "County")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public virtual County FestivalCounty { get; set; }

    [Required]
    [Display(Name = "Town")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public virtual Town FestivalTown { get; set; }

    [Required]
    [Display(Name = "Festival Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public virtual FestivalType FType { get; set; }

    [Display(Name = "Festival Logo")]
    [DataType(DataType.Upload)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string FestivalLogo { get; set; }

    [Display(Name = "Description"), StringLength(200)]
    public string Description { get; set; }

    public ICollection<Events> Events { get; set; }
    public IEnumerable<Events> EventsOrdered
    {
        get { return Events.OrderBy(e => e.EventsDate); }
    }

    public int UserID { get; set; }

    [ForeignKey("UserID")]
    public virtual UserProfile User { get; set; }

}

视图模型

public class FestivalVM
{
    public int FestivalID { get; set; }

    [Required]
    [Display(Name = "Town")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public Dictionary<int, string> Towns { get; set; }

    [Required]
    [Display(Name = "County")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public Dictionary<int, string> County { get; set; }

    [Required]
    [Display(Name = "Festival Type")]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public Dictionary<int, string> FestivalType { get; set; }

    public int SelectedTown { get; set; }
    public int SelectedCounty { get; set; }
    public int SelectedFestivalType { get; set; }

    [Required]
    [Display(Name = "Festival Name"), StringLength(100)]
    [DisplayFormat(ApplyFormatInEditMode = true)]
    public string FestivalName { get; set; }

    [Required]
    [Display(Name = "Start Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime startDate { get; set; }

    [Required]
    [Display(Name = "End Date")/*, DataType(DataType.Date)*/]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime endDate { get; set; }

    public HttpPostedFileWrapper imageFile { get; set; }

    [Display(Name = "Festival Logo")]
    public string festivalLogo { get; set; }

    public UserProfile UserID { get; set; }
    [Display(Name = "Description"), StringLength(200)]
    public string sDescription { get; set; }

    [Required]
    [Display(Name = "Location")]
    public DbGeography Location { get; set; }
}

1 个答案:

答案 0 :(得分:1)

您可以进行一些更改以允许发布数据:

视图

在发布数据时将@using (Html.BeginForm())更改为此行:using (Html.BeginForm("Create2", "YourControllerName", FormMethod.Post, new {enctype="multipart/form-data"}))

动作

应该是这样的:

public ActionResult Create2(FestivalVM model, HttpPostedFileBase imageFile)
{
    if (ModelState.IsValid != true)
    {
        if (model.SelectedFestivalType != -1)
        {
            //db.save stuff from create.
            Festival Newfestival = new Festival();
            Newfestival.EndDate = model.endDate;
            Newfestival.FestivalCounty = db.Counties.Where(p => p.ID == model.SelectedCounty).Single();
            Newfestival.FestivalName = model.FestivalName;
            Newfestival.Description = model.sDescription;
            Newfestival.FType = db.FestivalTypes.Where(p => p.ID == model.SelectedFestivalType).Single();
            Newfestival.StartDate = model.startDate;
            Newfestival.Location = model.Location;
            Newfestival.FestivalTown = db.Towns.Where(p => p.ID == model.SelectedTown).Single();
            Newfestival.UserID = WebSecurity.CurrentUserId;

            if (Request.Files.Count > 0)
            {
                string fileName = Guid.NewGuid().ToString();
                string serverPath = Server.MapPath("~\\Content\\FestivalLogo");
                Bitmap newImage = new Bitmap(Request.Files["imageFile"].InputStream);
                newImage.Save(serverPath + "\\" + fileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                Newfestival.festivalLogo = "Content/FestivalLogo/" + fileName + ".jpg";

                db.Festivals.Add(Newfestival);
                db.SaveChanges();
                return RedirectToAction("Details", new {id = Newfestival.FestivalId});
            }
            else
            {
                db.Festivals.Add(Newfestival);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = Newfestival.FestivalId });   
            }
        }
        ModelState.AddModelError("", "No Festival Type Picked");
    }
    model.County = db.Counties.ToDictionary(p => p.ID, q => q.Name);
    model.FestivalType = db.FestivalTypes.ToDictionary(p => p.ID, q => q.FType);
    model.FestivalType.Add(-1, "--- Add New Festival Type ---");
    model.Towns = db.Towns.ToDictionary(p => p.ID, q => q.Name);
    model.startDate = DateTime.Now;
    model.endDate = DateTime.Now;
    return View(model);
}

我希望它会有所帮助