Click here to Skip to main content
15,891,645 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:

Hi i am using code first. It returning null value to controller when uploading image.

Here is my class file

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MVC.Model
{
    public class Photo
    {
        public int PhotoId { get; set; }
        public int UserId { get; set; }
        public string PhotoCategory { get; set; }
        public string PhotoUrl { get; set; }
        public string PhotoName { get; set; }
        public virtual ICollection<User> Users { get; set; }
    }
}

ViewModel
C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MVC.Web.ViewModels
{
    public class PhotoFormModel
    {
        public int PhotoId { get; set; }
        [Required(ErrorMessage = "Photo Name Required")]
        //[Display(Name = "Movie Name")]
        public string PhotoName { get; set; }
        [Required(ErrorMessage = "Upload Photo")]
        public IEnumerable<HttpPostedFileBase> PhotoUrl { get; set; }
        public string PhotoCategory { get; set; }
    }
}


Controller

C#
[HttpPost]
       [ValidateAntiForgeryToken]
       public ActionResult Save(PhotoFormModel form,HttpPostedFileBase file)
       {
           if (file != null)
           {
               string pic = System.IO.Path.GetFileName(file.FileName);
               //string path = System.IO.Path.Combine(
               //                       Server.MapPath("~/Photos/"), pic);
               //// file is uploaded
               //file.SaveAs(path);
               string ImageName = System.IO.Path.GetFileName(file.FileName);
               string physicalPath = Server.MapPath("~/images/" + ImageName);

               // save image in folder
               file.SaveAs(physicalPath);

               // save the image path path to the database or you can send image
               // directly to database
               // in-case if you want to store byte[] ie. for DB
               using (MemoryStream ms = new MemoryStream())
               {
                   file.InputStream.CopyTo(ms);
                   byte[] array = ms.GetBuffer();
               }

           }
           //if (ModelState.IsValid)
           if (ModelState.ContainsKey("{key}"))
               ModelState["{key}"].Errors.Clear();
           {
               Mapper.CreateMap<PhotoFormModel, CreateOrUpdatePhotoCommand>();
               var command = Mapper.Map<PhotoFormModel, CreateOrUpdatePhotoCommand>(form);
               IEnumerable<ValidationResult> errors = commandBus.Validate(command);
               //ModelState.AddModelErrors(errors);
               if (ModelState.IsValid)
               {
                   var result = commandBus.Submit(command);
                   if (result.Success) return RedirectToAction("Index");
               }
           }
           //if fail
           if (form.PhotoId == 0)
               return View("Create", form);
           else
               return View("Edit", form);
       }


Create.cshtml
C#
@model MVC.Web.ViewModels.PhotoFormModel
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Save", "Photo", FormMethod.Post,
                            new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Event</legend>     

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

        <div class="editor-label">
            @Html.LabelFor(model => model.PhotoName)
        </div>
        <div class="editor-field">
             @Html.EditorFor(model => model.PhotoName)
            @Html.ValidationMessageFor(model => model.PhotoName)
</div>
<div class="editor-label">
            @Html.LabelFor(model => model.PhotoUrl)
        </div>
        <div class="editor-field">
         <input type="file" name="file" id="file" style="width: 100%;" /> 
    <input type="submit" value="Upload" class="submit" />             @Html.ValidationMessageFor(model => model.PhotoUrl)
</div>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>


Problem is in save action viewmodel showing null value for image url but file object is showing url value
Posted

1 solution

Sindhu,

C#
@Html.LabelFor(model => model.PhotoUrl)


Will not send the value to back to controller.

Add a hidden field for the same and it should work

C#
@Html.HiddenFor(model => model.PhotoUrl)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900