错误在MVC中上传图像文件? (找不到答案)

时间:2013-12-09 18:40:39

标签: c# asp.net-mvc

在我的MVC网络应用程序中,我试图在向数据库提交新记录时上传文件,但每当发生这种情况时,我都会收到“对象引用未设置为对象上的实例”错误。以下是我的模型:

public class MenteeViewModel
{

    public mentee mentee { get; set; }
    public guardian guardian { get; set; }
    public address address { get; set; }        
    public email email { get; set; }
    public user users { get; set; }
    public phnumber phnumber { get; set; }                
    public econtact econtact { get; set; }        

    [Display(Name = "School System")]
    public int SelectedSSystemId { get; set; }
    public IEnumerable<SelectListItem> SSystemItems { get; set; }

    [Display(Name = "School")]
    public int SelectedSchoolId { get; set; }
    public IEnumerable<SelectListItem> SchoolItems { get; set; }

    public ssystem ssystems { get; set; }
    public school  schools{ get; set; }

    //This is for UPLOADING image and inserting image information to database
    public HttpPostedFileBase File { get; set; }
    public image image { get; set; }
}

以下是我实际尝试上传文件的控制器代码部分:

 [HttpPost]
    public ActionResult Create(MenteeViewModel menteeViewModel, HttpPostedFileBase file )
    {

        if (ModelState.IsValid)
        {
            var regModel = new RegisterModel();

            try
            {
                DateTime now = DateTime.Now;
                menteeViewModel.address.CreatedOn = now;
                menteeViewModel.guardian.CreatedOn = now;
                menteeViewModel.econtact.CreatedOn = now;
                menteeViewModel.email.CreatedOn = now;
                menteeViewModel.phnumber.CreatedOn = now;

                menteeViewModel.mentee.addresses.Add(menteeViewModel.address);
                menteeViewModel.mentee.guardians.Add(menteeViewModel.guardian);
                menteeViewModel.mentee.econtacts.Add(menteeViewModel.econtact);
                menteeViewModel.mentee.emails.Add(menteeViewModel.email);
                menteeViewModel.mentee.phnumbers.Add(menteeViewModel.phnumber);



                Regex pattern = new Regex("[-/]");
                var strDob = (DateTime) menteeViewModel.mentee.dob;
                var newDate = strDob.ToShortDateString();
                newDate = pattern.Replace(newDate, "");


                regModel.UserName = menteeViewModel.email.email_address;
                regModel.Password = newDate;
                WebSecurity.CreateUserAndAccount(regModel.UserName, regModel.Password);
                Roles.AddUsersToRole(new[] {regModel.UserName}, "User");

                menteeViewModel.mentee.active_flag = "N";
                menteeViewModel.mentee.flag3 = menteeViewModel.schools.school_id.ToString();
                menteeViewModel.mentee.CreatedOn = now;

                var vfileName = Guid.NewGuid().ToString() + Path.GetFileName(menteeViewModel.image.image_path);
                var path = Path.Combine(Server.MapPath("~/App_Data"), vfileName);
                menteeViewModel.File.SaveAs(path);

                menteeViewModel.image.image_path = path;
                menteeViewModel.mentee.images.Add(menteeViewModel.image);

                db.mentees.Add(menteeViewModel.mentee);
                db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine(" - Property: \"{0}\", Error: \"{1}",
                        ve.PropertyName, ve.ErrorMessage);
                    }


                }

                throw;
            }



            return RedirectToAction("Index");

        }

        return Create();
    }

以下是视图:

BEMentoring.ViewModels.MenteeViewModel

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>



@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>MenteeViewModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.first_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.mentee.first_name)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.middle_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.mentee.middle_name)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.last_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.mentee.last_name)
    </div>

    <!-- Gender, DOB, Class Grade !-->
    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.gender)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.mentee.gender)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.dob)
    </div>
    <div class="editor-field">
       @Html.JQueryUI().DatepickerFor(model => model.mentee.dob).ChangeYear(new YearDefinition(-20, RelativeTo.SelectedYear), new YearDefinition(2012)).DateFormat("yyyy-mm-dd")
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.mentee.class_grade)
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.mentee.class_grade)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.address.address1)
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.address.address1)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.address.city)
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.address.city)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.address.state)
    </div>

    <div class="editor-field">
        @Html.EditorFor(model => model.address.state)
    </div>



    <div class="editor-label">
        @Html.LabelFor(model => model.ssystems.ssystem_id)
    </div>        
    <div class="editor-field">
       @Html.DropDownListFor(model => model.ssystems.ssystem_id, new SelectList(ViewBag.SSystems as System.Collections.IEnumerable, "ssystem_id","ssystem_name"),
       "--Select One--", new {id = "ddlSystem"})
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.schools.school_id)
    </div>        
    <div class="editor-field">
       @Html.DropDownListFor(model => model.schools.school_id, new SelectList(ViewBag.Schools as System.Collections.IEnumerable, "school_id","school_name"),
       "--Select One--", new {id = "ddlSchool"})
    </div>

    <div class="editor-label">
        @Html.LabelFor(mode => Model.econtact.first_name)
    </div>        
    <div class="editor-field">
       @Html.EditorFor(model => model.econtact.first_name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(mode => Model.econtact.last_name)
    </div>        
    <div class="editor-field">
       @Html.EditorFor(model => model.econtact.last_name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.econtact.phone)
    </div>        
    <div class="editor-field">
       @Html.EditorFor(model => model.econtact.phone)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.email.email_address)
    </div>        
    <div class="editor-field">
       @Html.EditorFor(model => model.email.email_address)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.phnumber.area_code)
    </div>        
    <div class="editor-field">
       @Html.EditorFor(model => model.phnumber.area_code)
       @Html.EditorFor(model => model.phnumber.phone)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.guardian.first_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.guardian.first_name)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.guardian.middle_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.guardian.middle_name)
    </div>


    <div class="editor-label">
        @Html.LabelFor(model => model.guardian.last_name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.guardian.last_name)
    </div>

    <div>
        @Html.LabelFor(model => model.File)
        @Html.TextBoxFor(model => model.image.image_path, new {type = "file"})

    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

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

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

我已经搜索过,但未能找到这个问题的有用答案。如果有一个可以帮助我,我错过了请帮助!提前致谢

2 个答案:

答案 0 :(得分:1)

你这样做:

<div>
    @Html.LabelFor(model => model.File)
    @Html.TextBoxFor(model => model.image.image_path, new {type = "file"})
</div>

将其改为:

<div>
    @Html.LabelFor(model => model.File)
    <input name="file" type="file">
</div>

这应映射到您的viewmodel File属性。顺便说一句,这个名字并不是最好的...但它应该有效。

在您的控制器中,您接收已发布的文件作为参数...而不是模型本身...所以您需要从该参数中获取它。

答案 1 :(得分:0)

使用HttpPostedFileBase file参数处理文件。我发现您发布的代码中缺少边界检查。请务必检查null,其中对象可以为null,如本例所示。