简体   繁体   中英

Error: No parameterless constructor defined for this object

I am trying to use Action-[HttpPost] in my ASP MVC project however the Post Action doesn't seems to work.After Submit button Page will showing Error.

Following is my model:

public class bcSlider
{
    public int sliderID { get; set; }
    public string sliderImage { get; set; }
}

Following is my ManageOperations:

 public class MngSlider
 {
  public int insertSlider(bcSlider obj)
    {
        int condition = 0;
        try
        {
            SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ospDB"].ConnectionString);
            SqlCommand cmd = new SqlCommand("usp_InsertConfrence", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@SliderImage", obj.ImageName);
            if (con.State.Equals(ConnectionState.Closed))
                con.Open();
            condition = cmd.ExecuteNonQuery();
            con.Close();
            if (condition > 0)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  }

Following is Controller:

public class AdminSliderController : Controller
{
    bcSlider modelSlider = new bcSlider();
    MngSlider objSlider = new MngSlider();

  //---------------INSERT---------------//
    // GET: /AdminSlider/AddSlider
    public ActionResult AddSlider()
    {
        bcSlider mSlider = new bcSlider();
        return View(mSlider);
    }


    // POST: /AdminSlider/AddSlider
    [HttpPost]
    public ActionResult AddSlider(HttpPostedFile file, bcSlider mSlider)
    {
            if (ModelState.IsValid)
            {
                //File Available Verification
                if (file != null && file.ContentLength > 0)
                {
                    string fileName = Path.GetFileName(file.FileName);  //FileName
                    string fileExtension = Path.GetExtension(fileName); //FileExtension

                    //Extension Verification
                    if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".pdf" || fileExtension.ToUpper() == ".JPG" || fileExtension.ToUpper() == ".JEPG" || fileExtension.ToUpper() == ".PNG" || fileExtension.ToUpper() == ".PDF")
                    {
                        //FileSize Verification
                        int length = file.ContentLength;
                        if (length <= 1000)
                        {
                            string filepath = Path.Combine(Server.MapPath("~/ImagesDirectory/"), fileName); //FilePath
                            file.SaveAs(filepath);
                            objSlider.insertSlider(mSlider); //Insert to DB
                            ViewBag.Message = "<script>alert('File  Inserted Successfully !')</script>";
                            ModelState.Clear();
                        }
                        else
                        {
                            ViewBag.SizeMessage = "<script>alert('Size Should be of 1MB !')</script>";
                        }
                    }
                    else
                    {
                        ViewBag.ExtensionMessage = "<script>alert('File Not Supported !')</script>";
                    }
                }
                else
                {
                    ViewBag.Message = "<script>alert('Invalid File !')</script>";
                }
            }
            else
            {
                ViewData["result"] = "Registration Not Successful";
            }
                   return RedirectToAction("AddSlider");

    }
   }
 }

Following is htmlcs:

@model OspWebsite.Models.bcSlider

@{
ViewBag.Title = "AddSlider";
Layout = "~/Views/Shared/LayoutAdmin.cshtml";
}

<div class="content-header">

<!-- Page Name -->
<div class="container-fluid">
    <div class="row mb-2">
        <div class="col-sm-6">
            <h1 class="m-0 text-dark">Slider</h1>
        </div><!-- /.col -->
        <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
                <li class="breadcrumb-item"><a href="#">Home</a></li>
                <li class="breadcrumb-item active">Slider</li>
            </ol>
        </div><!-- /.col -->
    </div><!-- /.row -->
</div>
@Html.Raw(ViewBag.Message)
@Html.Raw(ViewBag.SizeMessage)
@Html.Raw(ViewBag.ExtensionMessage)
@using (Html.BeginForm("AddSlider", "AdminSlider", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Input Forms -->
<div class="row">
    <div class="offset-md-1 mt-5 col-md-10">
        <div class="card card-success">
            <div class="card-header">
                <h3 class="card-title">Add New Slider</h3>
                <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-widget="maximize"><i class="fas fa-expand"></i></button>
                    <button type="button" class="btn btn-tool" data-widget="collapse"><i class="fas fa-minus"></i></button>
                </div>
                <!-- /.card-tools -->
            </div>
            <!-- /.card-header -->
            <div class="card-body">
                <div class="card-body">
                    <div class="form-group">
                        <div class="col-sm-12 ">
                            <label for="inputEmail3"  class="col-sm-4 control-label">Select Slider</label>
                            <div class="custom-file">
                                <label class="custom-file-label" for="exampleInputFile"></label>
                                <input type="file" name="sliderImage" value=@Model.sliderImage class="custom-file-input" id="exampleInputFile">
                            </div>
                        </div>
                    </div>
                </div>
                <!-- /.card-body -->
            </div><div class="card-footer">
                <button type="submit" class="btn btn-success">Upload</button>
                <button type="submit" class="btn btn-default float-right">Cancel</button>
            </div>
            <!-- /.card-footer -->
            <!-- /.card-body -->
        </div>
        <!-- /.card -->
    </div>
    <!-- /.col -->
</div>
   }

 </div>

The GET Action is Calling But POST Action is Showing Error. i am inserting Image in Database.

You are having the error because of the parameter you are passing in the controller HttpPostedFile

HttpPostedFileBase and HttpPostedFile

are definitely not the same.

Change your method to

[HttpPost]
public ActionResult AddSlider(HttpPostedFileBase sliderImage, bcSlider mSlider)
{
     //your code here.
}

Notice that I used sliderImage because that was also what you have in your form.

Again Your form, which I don't know if it was a typo error is setting the value of a file-input

<input type="file" name="sliderImage" value=@Model.sliderImage class="custom-file-input" id="exampleInputFile">

You are not supposed to do that.

Again and on lighter note, if it is also not a typo, you don't have any attribute in you class obj.ImageName but you have the below in your insertSlider method

cmd.Parameters.AddWithValue("@SliderImage", obj.ImageName);

For more on HttpPostedFileBase and HttpPostedFile and see here

That's all for now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM