Adding to a table using MVC 5, and reset Id after deleting records

O. Haifa

I have 2 questions:

First I wrote a code to add doctors to database, at the beginning the code worked fine but after adding validation the doctor information does not added to table.. when I press add button the URL goes to: /Doctors/Save Why the data does not saved in database? And why after I pressed Add button the program does not redirect me to Add view?

In controller there Add() action is for the Add view which contains the adding form.. Save() action is for the Html.BeginForm("Save","Doctors") that is inside the Add view..

Here is my code:

public ActionResult Add()
    {  return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Save(Doctor doctor)
    {
        if (!ModelState.IsValid)
        {
            var viewModel = new DoctorViewModel
            {
                Doctor = doctor

            };
            return View("Add", viewModel);
        }

      if(doctor.Id == 0) {
      _context.Doctors.Add(doctor);
      _context.SaveChanges();
      return Redirect("Add");
        }
      else
      {
          var doctorInDb = _context.Doctors.Single(c => c.Id == doctor.Id);
          doctorInDb.Name = doctor.Name;
          doctorInDb.Symbol = doctor.Symbol;
          doctorInDb.Office = doctor.Office;
          doctorInDb.Phone = doctor.Phone;
          doctorInDb.Email = doctor.Email;
          _context.SaveChanges();
          return Redirect("Add");
        }

       } 

Add view:

@model Project.ViewModels.DoctorViewModel

@{
    ViewBag.Title = "Add";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Adding a Doctor</h2>

@using (Html.BeginForm("Save", "Doctors"))
{
    <div class="form-group">

        @Html.LabelFor(m => m.Doctor.Name)
        @Html.TextBoxFor(m => m.Doctor.Name , new { @class = "form-control"})
        @Html.ValidationMessageFor(m => m.Doctor.Name)
    </div>

    <div class="form-group">

        @Html.LabelFor(m => m.Doctor.Symbol)
        @Html.TextBoxFor(m => m.Doctor.Symbol, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Doctor.Symbol)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Doctor.Phone)
        @Html.TextBoxFor(m => m.Doctor.Phone, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Doctor.Phone)
    </div>


    <div class="form-group">
        @Html.LabelFor(m => m.Doctor.Office)
        @Html.TextBoxFor(m => m.Doctor.Office, new { @class = "form-control" })
    </div>



    <div class="form-group">
        @Html.LabelFor(m => m.Doctor.Email)
        @Html.TextBoxFor(m => m.Doctor.Email, new { @class = "form-control" })
    </div>

    @Html.HiddenFor(m => m.Doctor.Id)
    @Html.AntiForgeryToken()
    <button type="submit" class="btn btn-primary"> <h5> Add </h5> </button>     @Html.ActionLink("Go to doctors list", "DoctorList")
}

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

        }

Second question:

Can I reset the Id, after deleting all records from table, from the controller?

Here is my reset code:

public ActionResult Reset()
    {
        _context.PSRs.RemoveRange(_context.PSRs);

        _context.SaveChanges();
        return Redirect("PSR");
    }

Thanks!

dime2lo

Well, for what you have said I believe that:

First I wrote a code to add doctors to database, at the beginning the code worked fine but after adding validation the doctor information does not added to table.. when I press add button the URL goes to: /Doctors/Save Why the data does not saved in database?

It looks like the reason the data is not saved in database is because your Model is invalid:

    if (!ModelState.IsValid)
    {
        var viewModel = new DoctorViewModel
        {
            Doctor = doctor

        };
        return View("Add", viewModel);
    }

So you can debug your code to see the reason why it is invalid. If you want, you can insert this code:

var message = string.Join(" | ", ModelState.Values
    .SelectMany(v => v.Errors)
    .Select(e => e.ErrorMessage));

before var viewModel and a breakpoint on it so you don´t need to navigate in the properties during debug.

And why after I pressed Add button the program does not redirect me to Add view?

In controller there Add() action is for the Add view which contains the adding form.. Save() action is for the Html.BeginForm("Save","Doctors") that is inside the Add view..

You are not being redirect to the "Add view" because you are not saving doctor successfully (ModelState is invalid) therefore it just renders Add view (URL keeps as /Doctors/Save) but not redirect to it.

Second question:

Can I reset the Id, after deleting all records from table, from the controller?

Don´t know the answer for this one, maybe you should have splitted the question in two, so people can answer to one question but not to the other one.

Regards,

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

Reset identity seed after deleting records in SQL Server

From Dev

Deleting multiple records in a table using join in Peewee?

From Dev

deleting records from table using SQLAlchemy

From Dev

Deleting database records MVC

From Dev

reset id(primary key) after deleting record in sql

From Dev

Reset id count after table delete()

From Dev

Reset id count after table delete()

From Dev

Deleting all table records from core data database using relationship

From Dev

SQLite - no such table: while using CTE for deleting duplicate records

From Dev

Adding a role for user after registration in MVC 5

From Dev

Calculate automatically in a table using jquery when adding or deleting rows

From Dev

I want to save an ID from a table to another table using asp.net mvc 5

From Dev

I want to save an ID from a table to another table using asp.net mvc 5

From Dev

INSERT statement conflicted with the FOREIGN KEY constraint even after deleting the records from the child table

From Dev

Userform to delete specific records from table always duplicates the last record after deleting a specific record

From Dev

Adding and deleting rows in dynamic table in Asp.net mvc razor view

From Dev

Reset auto_increment after deleting row

From Dev

"Reset" buildNumber after deleting old builds in TeamCity

From Dev

Reset rowid field after deleting rows

From Dev

Error adding multiple records MVC

From Dev

Error while adding data to MS-SQL by using Asp.Net MVC-5 after hosting it in IIS

From Dev

Renumbering the remaining records after deleting one of them

From Dev

Deleting Records in SQL server table prior to insert

From Dev

deleting records from a table where there is an inner join

From Dev

Deleting records with number repeating more than 5

From Dev

Deleting table row by id with jQuery

From Dev

Adding routing in MVC 5

From Dev

Reloading KieSession after adding/deleting Rules in KieBase

From Dev

Laravel migrate:rollback adding and deleting table columns

Related Related

  1. 1

    Reset identity seed after deleting records in SQL Server

  2. 2

    Deleting multiple records in a table using join in Peewee?

  3. 3

    deleting records from table using SQLAlchemy

  4. 4

    Deleting database records MVC

  5. 5

    reset id(primary key) after deleting record in sql

  6. 6

    Reset id count after table delete()

  7. 7

    Reset id count after table delete()

  8. 8

    Deleting all table records from core data database using relationship

  9. 9

    SQLite - no such table: while using CTE for deleting duplicate records

  10. 10

    Adding a role for user after registration in MVC 5

  11. 11

    Calculate automatically in a table using jquery when adding or deleting rows

  12. 12

    I want to save an ID from a table to another table using asp.net mvc 5

  13. 13

    I want to save an ID from a table to another table using asp.net mvc 5

  14. 14

    INSERT statement conflicted with the FOREIGN KEY constraint even after deleting the records from the child table

  15. 15

    Userform to delete specific records from table always duplicates the last record after deleting a specific record

  16. 16

    Adding and deleting rows in dynamic table in Asp.net mvc razor view

  17. 17

    Reset auto_increment after deleting row

  18. 18

    "Reset" buildNumber after deleting old builds in TeamCity

  19. 19

    Reset rowid field after deleting rows

  20. 20

    Error adding multiple records MVC

  21. 21

    Error while adding data to MS-SQL by using Asp.Net MVC-5 after hosting it in IIS

  22. 22

    Renumbering the remaining records after deleting one of them

  23. 23

    Deleting Records in SQL server table prior to insert

  24. 24

    deleting records from a table where there is an inner join

  25. 25

    Deleting records with number repeating more than 5

  26. 26

    Deleting table row by id with jQuery

  27. 27

    Adding routing in MVC 5

  28. 28

    Reloading KieSession after adding/deleting Rules in KieBase

  29. 29

    Laravel migrate:rollback adding and deleting table columns

HotTag

Archive