0

I would appreciate some help here. I am trying to create a ASP.NET web app using MVC 5 EF. I have scaffolded my model to generate views and controller and apparently the create button/ insert button doesn't respond (doesn't insert values into the db but i can insert values directly on the db interface). I am suspecting its something to do with the GUID value that i use as a primary key.

Here are my codes model

public class Supplier
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid SupplierId { get; set; }
    [Required]
    [Display(Name = "Supplier Name")]
    [StringLength(100, ErrorMessage = "Name cannot be longer than 30 characters.")]
    [Remote("doesSupplierExist", "Supplier", HttpMethod = "POST", ErrorMessage = "Duplicate Supplier Name Detected")]
    public string Name { get; set; }
    [Required]
    [Display(Name = "Supplier phone Number")]
    public int Phone { get; set; }
    [Required]
    [Display(Name = "Supplier Email")]
    [StringLength(100, ErrorMessage = "Email cannot be longer than 50 characters.")]
    public string Email { get; set; }
    [Required]
    [Display(Name = "Supplier Location")]
    [StringLength(100, ErrorMessage = "Location cannot be longer than 50 characters.")]
    public string Location { get; set; }

}

controller

public class SuppliersController : Controller
{
   private ApplicationDbContext db = new ApplicationDbContext();

    // GET: Suppliers
    public async Task<ActionResult> Index()
    {
        return View(await db.Suppliers.ToListAsync());
    }

    // GET: Suppliers/Details/5
    public async Task<ActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // GET: Suppliers/Create
    public ActionResult Create()
    {
        return View();
    }

    // POST: Suppliers/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include ="SupplierId,Name,Phone,Email,Location")] Supplier supplier)
    {
        if (ModelState.IsValid)
        {
            supplier.SupplierId = Guid.NewGuid();
            db.Suppliers.Add(supplier);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        return View("Index");
    }

    // GET: Suppliers/Edit/5
    public async Task<ActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // POST: Suppliers/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "SupplierId,Name,Phone,Email,Location")] Supplier supplier)
    {
        if (ModelState.IsValid)
        {
            db.Entry(supplier).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(supplier);
    }

    // GET: Suppliers/Delete/5
    public async Task<ActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Supplier supplier = await db.Suppliers.FindAsync(id);
        if (supplier == null)
        {
            return HttpNotFound();
        }
        return View(supplier);
    }

    // POST: Suppliers/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(Guid id)
    {
        Supplier supplier = await db.Suppliers.FindAsync(id);
        db.Suppliers.Remove(supplier);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

Create View

@{
  ViewBag.Title = "Create";
  Layout = "~/Views/Shared/_dashboardLayout.cshtml";
 }
  <h2>Create</h2>

 @using (Html.BeginForm()) 
  {
   @Html.AntiForgeryToken()


<div class="form-horizontal">
    <h4>Supplier</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Location, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Location, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Location, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

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

Migration

CreateTable("dbo.Suppliers",
            c => new
                {
                    SupplierId = c.Guid(nullable: false, identity: true, 
                    defaultValueSql: "newsequentialid()"),
                    Name = c.String(nullable: false, maxLength: 100),
                    Phone = c.Int(nullable: false),
                    Email = c.String(nullable: false, maxLength: 100),
                    Location = c.String(nullable: false, maxLength: 100),
                })
            .PrimaryKey(t => t.SupplierId);

1 Answers1

0

You need to remove the following attribute from your primary key.

DatabaseGenerated(DatabaseGeneratedOption.Identity)

You're providing a value, you don't need the database to generate one for you. Besides, to the best of my knowledge you can't have a GUID (uniqueidentifier in SQL) as an Identity column.

Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • Thanks for the response though after the suggested changes, it doesn't insert values to the database still. – Albertz Ace Jun 14 '18 at 08:26
  • Are you sure there is no exception being thrown? Are you sure the `ModelState.IsValid` is returning `true`? You have the `Email` column marked as `[Required]` but you're never setting it to a value in the `Create` method. – Craig W. Jun 14 '18 at 14:06
  • I dont understand when you say I am not setting the value for Email. All am doing is scaffolding from the model. Kindly explain further – Albertz Ace Jun 14 '18 at 15:50
  • It seems like a pretty obvious comment. You have a line of code that says, `supplier.SupplierId = Guid.NewGuid();`. Nowhere do you have a line of code that says `supplier.Email = something`. Again, have you debugged to see if an exception is being thrown? – Craig W. Jun 14 '18 at 23:43