Click here to Skip to main content
15,882,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Team

I am having an issue with my crud application, basically this application uses business logic, entity framework for specific reason of the requirement. But the problem is when View is created and try to run this file 'Order/Edit.cshtml just to check if my application is running. "
No parameterless constructor defined for this object.
. At first i thought this had to do with routing and by default routing is Home/Index. Does this mean i have an empty constructor to my Controller or Model? Please advice so can make an fix and continue.

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SalesOrder.Models;
using SalesOrder.Services;


namespace SalesOrder.Controllers
{
    public class OrderController : Controller
    {
        // declaring some objects.
        private readonly OrderServices _orderServices;

        // constructor.
        public OrderController(OrderServices orderServices)
        {
            _orderServices = orderServices;
        }
        
        
        // GET: Order
        public ActionResult Index()
        {
            List<OrderViewModel> orders = _orderServices.GetOrders();
            return View(orders);
        }

        // GET:Order/Edit/5
        public ActionResult Edit(int id)
        {
            OrderViewModel order = _orderServices.GetOrderById(id);


            if(order == null)
            {
                return HttpNotFound();
            }

            return View(order);
        }

        // POST:Order/Edit/5.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(OrderViewModel order)
        {
            if(ModelState.IsValid)
            {
                _orderServices.UpdateOrder(order);
                return RedirectToAction("Index");
            }
            return View(order);
        }
    }
}

// Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SalesOrder.Models
{
    public class OrderViewModel
    {
        public int OrderId { get; set; }
        public string OrderNumber { get; set; }
        public DateTime OrderDate { get; set; }
        // Other order properties...
        public List<OrderLine> OrderLines { get; set; }
    }


    // Model representing a single order line
    public class OrderLine
    {
        public int OrderLineId { get; set; }
        public string ProductCode { get; set; }
        public int Quantity { get; set; }
        // Other order line properties...

        public int OrderId { get; set; } // Foreign key to Order table
        public virtual OrderViewModel Orders { get; set; } // Navigation property
    }

    // Model representing a customer
    public class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        // Other customer properties...

        public virtual ICollection<OrderViewModel> Orders { get; set; } // Collection of orders for a customer
    }

    // Model representing a product
    public class Products
    {
        public int ProductId { get; set; }
        public string ProductCode { get; set; }
        public string ProductName { get; set; }
        // Other product properties...

        public virtual ICollection<OrderLine> OrderLines { get; set; } // Collection of order lines for a product
    }

    public class OrderHeader
    {
        public string OrderNumber { get; set; }
        public string OrderType { get; set; }
        public string OrderStatus { get; set; }
        public string CustomerName { get; set; }
        public Nullable<System.DateTime> CreateDate { get; set; }

    }

    public class OrderHeaderStatus
    {
        public string OrderStatus { get; set; }
        public virtual ICollection<OrderHeader> OrderHeaders { get; set; }
    }

}

//Repository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SalesOrder.Models;

namespace SalesOrder.Repository
{
    public class OrderRepository
    {
        private readonly SalesOrderEntities __salesOrder;

        // constructor.
        public OrderRepository(SalesOrderEntities salesOrder)
        {
            __salesOrder = salesOrder;
        }

        // get all orders
        public List<OrderViewModel> GetOrders()
        {
            return __salesOrder.Orders.ToList();
        }

        // Get order by id.
        public OrderViewModel GetOrderById(int id)
        {
            return __salesOrder.Orders.FirstOrDefault(o => o.OrderId == id);
        }

        //Get order by id.
        public void UpdateOrder(OrderViewModel order)
        {
            __salesOrder.Entry(order).State = EntityState.Modified;
            __salesOrder.SaveChanges();
        }
    }
}

// Services.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using SalesOrder.Models;
using SalesOrder.Repository;

namespace SalesOrder.Services
{
    public class OrderServices
    {
        // creating some objects here.
        private readonly OrderRepository _orderRepository;

        // constructor.
        public OrderServices(OrderRepository orderRepository)
        {
            _orderRepository = orderRepository;
        }

        // get all orders.
        public List<OrderViewModel> GetOrders()
        {
            return _orderRepository.GetOrders();
        }

        // Get order by id.
        public OrderViewModel GetOrderById(int id)
        {
            return _orderRepository.GetOrderById(id);
        }

        // update an existing order.
        public void UpdateOrder(OrderViewModel order)
        {
            _orderRepository.UpdateOrder(order);
        }
    }
}

// Edit.cshtml
@model SalesOrder.Models.OrderViewModel


@using (Html.BeginForm("Edit", "Order", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <h2>Edit Order</h2>

    <div>
        @Html.LabelFor(model => model.OrderNumber)
        @Html.EditorFor(model => model.OrderNumber)
        @Html.ValidationMessageFor(model => model.OrderNumber)
    </div>

    <div>
        @Html.LabelFor(model => model.OrderDate)
        @Html.EditorFor(model => model.OrderDate)
        @Html.ValidationMessageFor(model => model.OrderDate)
    </div>

    <div>
        @Html.LabelFor(model => model.Customer)
        @Html.EditorFor(model => model.Customer)
        @Html.ValidationMessageFor(model => model.Customer)
    </div>

    <!-- Add additional fields for editing order details -->

    <input type="submit" value="Save" />
}
// SalesOrderEntities.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace SalesOrder
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using SalesOrder.Models;

    public partial class SalesOrderEntities : DbContext
    {
        public SalesOrderEntities()
            : base("name=SalesOrderEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<Customer> Customers { get; set; }
        public virtual DbSet<OrderHeader> OrderHeaders { get; set; }
        public virtual DbSet<OrderHeaderStatu> OrderHeaderStatus { get; set; }
        public virtual DbSet<OrderLine> OrderLines { get; set; }
        public virtual DbSet<Product> Products { get; set; }
        public virtual DbSet<ProductType> ProductTypes { get; set; }
        public virtual DbSet<OrderViewModel> Orders { get; set; }
    }
}
````Preformatted text`
Posted
Updated 4-Jun-23 18:19pm
v2

No parameterless constructor defined for this object.

This is quite clear...

This is a parameter constructor class:
C#
public class MyParameterClass
{
#region Constructors

    public MyParameterClass(int param1, int param2)
    {
    }

#end region
}

To fix, add a parameterless constructor to the class:
C#
public class MyParameterlessClass
{
#region Constructors

    public MyParameterlessClass() // parameterless constructor
    {
    }

    public MyParameterlessClass(int param1, int param2)
    {
    }

#end region
}
 
Share this answer
 
To add to what Graeme has said ...
When you create a class the system adds a hidden default parameterless constructor for you so that you can create instances:
C#
public partial class MyClass
   {
   public MyClass() {}  // Hidden constructor
   }
...
   MyClass foo = new MyClass();    // Calls the default constructor
If you create a constructor of any kind, the hidden default constructor is removed so that a parameterless constructor cannot be called unless you specifically allow it:
C#
public class MyClass
   {
   private string Name = "";
   public MyClass(string name) { Name = name;}  
   }
...
   MyClass foo = new MyClass();    // Causes an error
   MyClass foo = new MyClass("Joe Bloe"); // Calls your new constructor
If you think about it, that's kinda important: if you create a class that must have some information to do anything (a User class might need at least a Name for example, or Singleton class might need a private constructor instead of public) then unless the default constructor is removed it could still be called and that would defeat the whole idea.
 
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