Asp.net mvc 4 将图像保存到MVC4中的数据库

Asp.net mvc 4 将图像保存到MVC4中的数据库,asp.net-mvc-4,Asp.net Mvc 4,我正在尝试使用MVC4将图像文件名和位置保存到数据库中。有人能看出我错在哪里吗?我是mvc的新手,我是为客户构建mvc的。我在这一行“if(Request.Files.Count>0)”上放了一个断点,但它跳过了它并进入我的else语句 public ActionResult Create2(FestivalVM model) { if (ModelState.IsValid != true) { if (model.Selecte

我正在尝试使用MVC4将图像文件名和位置保存到数据库中。有人能看出我错在哪里吗?我是mvc的新手,我是为客户构建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>
@model MyFestival.Models.festival.m
@{
ViewBag.Title=“添加节日”;
Layout=“~/Views/Shared/Festival.cshtml”;
}
创造你的节日

@使用(Html.BeginForm()) { @Html.AntiForgeryToken()
  • 创建节日
    @ValidationSummary(true,null,new{@class=“alert-alert-danger”}) @LabelFor(model=>model.FestivalName,新的{@class=“controllabel col-md-2”}) @Html.TextBoxFor(model=>model.festival名称,新的{@class=“form control”,@style=“width:210px”}) @Html.ValidationMessageFor(model=>model.FestivalName,null,新的{@style=“color:red;”}) @LabelFor(model=>model.startDate,新的{@class=“controllabel col-md-2”}) @Html.TextBoxFor(model=>model.startDate,新的{@class=“form control datepicker”,@style=“width:250px”}) @Html.ValidationMessageFor(model=>model.startDate,null,new{@style=“color:red;”}) @LabelFor(model=>model.endDate,新的{@class=“controllabel col-md-2”}) @TextBoxFor(model=>model.endDate,新的{@class=“form control datepicker”,@style=“width:250px”}) @Html.ValidationMessageFor(model=>model.endDate,null,新的{@style=“color:red;”}) @LabelFor(model=>model.Towns,新{@class=“controllabel col-md-2”}) @DropDownListFor(p=>p.SelectedTown,Model.Towns.Select(p=>newselectListItem()) { Text=p.Value.ToString(), Value=p.Key.ToString(), 所选=错误 }), 新的 { @class=“表单控制”, @style=“宽度:210px”, 占位符=“----选择一个城镇--” }) @Html.ValidationMessageFor(model=>model.Towns,null,新{@style=“color:red;”}) @LabelFor(model=>model.County,新的{@class=“controllabel col-md-2”}) @DropDownListFor(p=>p.SelectedCounty,Model.country.Select(p=>newselectListItem)() { Text=p.Value.ToString(), Value=p.Key.ToString(), 所选=错误 }), 新的 { @class=“表单控制”, @style=“宽度:210px” }) @Html.ValidationMessageFor(model=>model.country,null,新的{@style=“color:red;”}) @LabelFor(model=>model.FestivalType,新的{@class=“controllabel col-md-2”}) @Html.DropDownListFor(p=>p.SelectedFestivalType,Model.FestivalType.Select(p=>newselectListItem() { Text=p.Value.ToString(), Value=p.Key.ToString(), 所选=错误 }), 新的 { @class=“表单控制”, @style=“宽度:210px;”, @onchange=“checkaddnew();” }) @Html.ValidationMessageFor(model=>model.FestivalType,null,新的{@style=“color:red;”}) @LabelFor(model=>model.sDescription,新的{@class=“controllabel col-md-2”}) @Html.TextAreaFor(model=>model.sDescription,新的{@class=“form control”,@style=“width:210px;”}) @ValidationMessageFor(model=>model.sDescription,null,新的{@style=“color:red;”}) @LabelFor(model=>model.Location,新的{@class=“controllabel col-md-2”}) @Html.TextAreaFor(model=>model.Location,新的{@class=“form control”,@style=“width:210px”}) @Html.ValidationMessageFor(model=>model.Location,null,新的{@style=“color:red;”}) @LabelFor(model=>model.festivallo,新的{@class=“controllabel col-md-2”}) @ActionLink(“返回列表”,“索引”,空,新{@class=“btn btn danger”}) } @Html.Partial(“CreateFestival-Type”,新的MyFestival.Models.Festival-TypeVM()) @节脚本{ @Scripts.Render(“~/bundles/jqueryval”) $(文档).ready(函数(){ $('#SelectedFestivalType')。更改(函数(){ if($(this).find(“:selected”).val()=-1){ $('myModal').modal('show'); } }); }); 函数ajaxResponse(数据){ 警报(“此操作有效,数据ID为:“+Data.festival-typeid”); var newOption=“”+数据名+”; $('#SelectedFestivalType')。追加(newOption); $('#myModal').modal('hide'); $(“#selectedFesticalType选项[value='”+data.festicalTypeId+“']”)attr(“selected”、“selected”); } ; $(文档).ready(函数(){ $(“#startDate”).datepicker(“setDate”、“+1”、{dateFormat:“dd/mm/yy”}).on('changeDate',函数
    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; }
    }
    
    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);
    }