Novice
Novice

Reputation: 558

Avoiding null or empty values to save in database using Entity Framework

I have an application where we are using entity framework and on button click an ajax call is made to save values.
Everything is working fine, but even if we try to click the save button, with no values, it gets saved in database as null or empty(takes space).
There is some minor error which I am overlooking, please help me out.
What I tried:

$.ajax({
            type: "POST",
            url: '~/SaveGroups',
            data: {
            GroupId: (GroupId == null ? -1 : GroupId),
            counterId: (counterId == null ? -1 : counterId),
            GroupCode: GroupCode,
            GroupDesc: GroupDescription
        },
            success: function (result) {
                if (result != null) {
                    $("#PartialGroupsTable").html(result.GroupsPageString);
                    $("#GCode").val('')             //GCode is the name of the textbox
                    $("#GDescription").val('');     //GDescription is the other textbox
                    GroupId = -1;
        }

        },
            complete: function () {
                $("#GCode").empty();
                $("#GDescription").empty();
        },
            error: function () {
                alert("Details Not Saved. Please try again later");
        }

        });

Thanx in advance.

Upvotes: 0

Views: 1835

Answers (2)

Alex Paven
Alex Paven

Reputation: 5549

If you expect to get -1 for GroupId or counterId and instead get something else, the reason is probably that the existing value is not null but perhaps an empty string. Check for that as well as checking for null/undefined. If that's not the problem then additional information may be needed.

For example:

GroupId: ((GroupId == null || GroupId == '') ? -1 : GroupId),

Upvotes: 1

Karthik Bammidi
Karthik Bammidi

Reputation: 1851

You have several options to fulfill your requirements, two of them are Client Side validation and server side validations that means you need to validate the data before send it to database for saving.. like

you have model classes right.. that represent your tables

public class User
{
[Required]
public string UserName{get; set;}
...
...
} 

suppose if you try to send null values to controllers or dbcontext it wont allows you to insert null values into it since it allows only non-null values.

and also you can do this as well using jquery

function buttonClick()
{
if($('#txtName').val()=='')
{
alert('Please enter name');
return false;
}
else
{
//make ajax call here
}
}

like this you can do it in many ways you can use unobtrusive javascript as well. Hope this helps

Upvotes: 1

Related Questions