locked
Error message not getting displayed RRS feed

  • Question

  • User1979860870 posted

    Hi

       I have below code but it Saves record with Blank Values

    public class Location
        {
            public Location()
            {
                CreatedOn = DateTime.Now;
                //CreatedBy = DateTime.Now;
            }
            [Key]
            public int Id { get; set; }
            [DataType(DataType.Text)]
            [RegularExpression(@"^[a-zA-Z'.\s]{1,25}$", ErrorMessage = "Special Characters not allowed")]
            [Required(ErrorMessage = "Please enter Location"), MaxLength(25)]
            [Display(Name = "Location Name")]
            public string Description { get; set; }
            public string IsActive { get; set; }
    
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
            public DateTime CreatedOn { get; set; }
            public DateTime CreatedBy { get; set; }
        }
    *********************************************************************
    
    public class LocationDB
        {
            string cs = ConfigurationManager.ConnectionStrings["Cnn"].ConnectionString;
            public List<Location> GetAllLocation()
            {
                List<Location> objLocation = new List<Location>();
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand com = new SqlCommand("sp_Location", con);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@Action", "R");
                    SqlDataReader rdr = com.ExecuteReader();
                    while (rdr.Read())
                    {
                        objLocation.Add(new Location
                        {
                            Description = rdr["Description"].ToString(),
                        });
                    }
                    return objLocation;
                }
            }
    
            public int Add(Location objLoc)
            {
                int i;
                using (SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    SqlCommand com = new SqlCommand("sp_Location", con);
                    com.CommandType = CommandType.StoredProcedure;
                    com.Parameters.AddWithValue("@Id", objLoc.Id);
                    com.Parameters.AddWithValue("@Description", objLoc.Description);
                    com.Parameters.AddWithValue("@Action", "C");
                    i = com.ExecuteNonQuery();
                }
                return i;
            }
    
        }
    
    function Add() {
        var objLocation = {
            Id: $('#Id').val().toUpperCase(),
            Description: $('#Description').val().toUpperCase()
        };
        $.ajax({
            url: "/Location/Add",
            data: JSON.stringify(objLocation),
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                loadData();
                $('#myModal').modal('hide');
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }
    <div class="box box-default">
        <div class="box-header with-border">
            @*<h2>Location Record</h2>*@
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Location</button><br /><br />
            <table class="table table-bordered table-hover" id="tblLocation">
                <thead>
                    <tr>
                        <th>
                            ID
                        </th>
                        <th>
                            Location
                        </th>
                        <th>
                            Action
                        </th>
                    </tr>
                </thead>
                <tbody class="tbody"></tbody>
            </table>
        </div>
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
    
                    <div class="modal-header">
                        <a class="close" data-dismiss="modal">×</a>
                        <h3>Contact Form</h3>
                    </div>
                    <div class="modal-body">
                        <form>
    
                            <div class="form-group">
                                <label for="Name">Location Id</label>
                                <input type="text" class="form-control" id="Id" placeholder="Location Id" />
                            </div>
                            <div class="form-group">
                                <label for="Name">Location Name</label>
                                <input type="text" class="form-control" id="Description" placeholder="Location Name" />
                            </div>
     
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
                        <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="~/ScriptsApp/Location.js"></script>

    Thanks

    Tuesday, May 25, 2021 1:59 PM

All replies

  • User475983607 posted

    The code is incomplete.  I'm guessing there is a bug in the stored procedure which you did not share.  Integers default to zero.  So an empty Id is odd unless your conclusion is incorrect.

    Also, the location model has more fields than what the AJAX function passes.

    I recommend using the Visual Studio debugger to single step through the code.  This is a lot easier and quicker than posting every little problem on a forum.

    https://docs.microsoft.com/en-us/visualstudio/debugger/debugger-feature-tour?view=vs-2019

    https://docs.microsoft.com/en-us/visualstudio/debugger/?view=vs-2019

    Lastly, as mentioned in your other thread.  The design approach is poor and leads to bugs and code that is hard to maintain.  Use separate stored procedures.

    Tuesday, May 25, 2021 6:59 PM
  • User1686398519 posted

    Hi jagjit saini, 

    Have you set a breakpoint to see if objLoc has a value?I suggest that you can set a breakpoint to view the value of objLoc.

    Based on the code you provided, I added the missing code and tested it, and found that data can be inserted.

    • Can you provide controller code and stored procedure if it is convenient for you?

    Below are the stored procedure and controller I tested.

    Stored procedure

    CREATE PROCEDURE [dbo].[sp_Location]
    	@Id int = 0,
    	@Description varchar,
    	@Action varchar
    AS
    	IF @Action = 'C' 
    		BEGIN  
    		    INSERT INTO 
    Location (Id,Description)  VALUES( @Id,@Description) END

    Controller

            [HttpPost]
            public ActionResult Add(Location objLoc)
            {
                LocationDB db = new LocationDB();
                db.Add(objLoc);
                return Json("",JsonRequestBehavior.AllowGet);
            }

    Best Regards,

    YihuiSun

    Wednesday, May 26, 2021 3:05 AM
  • User1979860870 posted

    Hi YihuiSun

       When i leave Description Blank it saves the record though in Data Annotations i have given it as required.

    public class Location
        {
            public Location()
            {
                CreatedOn = DateTime.Now;
            }
            [Key]
            public string Id { get; set; }
            [DataType(DataType.Text)]
            [RegularExpression(@"^[a-zA-Z'.\s]{1,25}$", ErrorMessage = "Special Characters not allowed")]
            [Required(ErrorMessage = "Please enter Location"), MaxLength(25)]
            [Display(Name = "Location Name")]
            public string Description { get; set; }
            public string IsActive { get; set; }
    
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
            public DateTime CreatedOn { get; set; }
            public DateTime CreatedBy { get; set; }
        }
    
    ************************************************
    function Add() {
        var objLocation = {
            Id: $('#Id').val().toUpperCase(),
            Description: $('#Description').val().toUpperCase()
        };
        $.ajax({
            url: "/Location/Add",
            data: JSON.stringify(objLocation),
            type: "POST",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                loadData();
                $('#myModal').modal('hide');
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }
    
    *******************************************
    <div class="box box-default">
        <div class="box-header with-border">
            <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Location</button><br /><br />
            <table class="table table-bordered table-hover" id="tblLocation">
                <thead>
                    <tr>
                        <th>
                            ID
                        </th>
                        <th>
                            Location
                        </th>
                        <th>
                            Action
                        </th>
                    </tr>
                </thead>
                <tbody class="tbody"></tbody>
            </table>
        </div>
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
    
                    <div class="modal-header">
                        <a class="close" data-dismiss="modal">×</a>
                        <h3>Contact Form</h3>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="form-group">
                                <label for="Name">Location Id</label>
                                <input type="text" class="form-control" id="Id" placeholder="Location Id" />
                            </div>
                            <div class="form-group">
                                <label for="Name">Location Name</label>
                                <input type="text" class="form-control" id="Description" placeholder="Location Name" />
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button>
                        <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="~/ScriptsApp/Location.js"></script>
    
    ******************************************************
    ALTER PROCEDURE [dbo].[sp_Location] 
    	-- Add the parameters for the stored procedure here
    	@Id nvarchar(4) = Null, 
    	@Description nvarchar(25) = Null, 
    	@IsActive nvarchar(1) = Null, 
    	@Action varchar(1)
    AS
    BEGIN
    	-- SET NOCOUNT ON added to prevent extra result sets from
    	-- interfering with SELECT statements.
    	SET NOCOUNT ON;
    
    	if @Action='C' 
    	Begin 
    		Insert into Location(Id,Description) values(@Id,@Description); 
    	End 
    END
    

    Thanks

    Wednesday, May 26, 2021 4:58 AM
  • User475983607 posted

    When i leave Description Blank it saves the record though in Data Annotations i have given it as required.

    My best guess is you did not write any code to handle validation errors in the controller.  There's certainly no code in the data access code, stored procedure or AJAX function.  Unfortunately you did not share the controller.   The standard pattern is below.

            [HttpPost]
            public ActionResult Index(ViewModel model)
            {
                if (ModelState.IsValid)
                {
                    // Save record
                }
    
                return Json(new { error = "Custom Error Message" });
            }

    https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.modelstate?view=aspnet-mvc-5.2

    You'll need to write code in the AJAX function that writes the error the screen.  You can also trigger the validation in JavaScript before submitting the AJAX POST.

    $("form").validate();

    Wednesday, May 26, 2021 10:22 AM