简体   繁体   中英

How to truncate extra string characters get from UI control before saving to database table?

I am having a MVC application in which i receive some data as a phone number from the textbox control. In the database table i have specified it's column size to (varchar 50). So if i insert more than 50 characters into the database system throw an error like: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

So i want to truncate all the extra character before saving it into database automatically without restricting its size on the UI control itself.

Below is the code when it try to save it into database using EF:

private void PresetNewContacts(List<ContactModel> contacts)
{
    contacts.ForEach(contact =>
    {
        if ((!string.IsNullOrEmpty(contact.CompanyName) || !string.IsNullOrEmpty(contact.ContactName)) && contact.TrnContact != null)
        {
            contact.PhoneNumber = contact.TrnContact.PhoneNumber;
            contact.EmailAddress = contact.TrnContact.EmailAddress;
            contact.NominatingEmployeeID = CargoSessionProvider.LoggedinUser.NominatingEmployeeID;
            contact.Company = contact.Company == "[New]" ? contact.CompanyName : contact.Company;

            //Save new contact in DB and update ContactID
            contact.TrnContact.ContactID = NominationService.SaveContact(contact);
        }
    });
}


/// <summary>
/// Saves the changes in the context
/// </summary>
public void SaveChanges()
{
    try
    {
        DbContext.SaveChanges();
    }
    catch (DbEntityValidationException ex)
    {
        throw ex;

    }
    catch (Exception ex)
    {
        throw;
    }

}

Since you are using MVC , another option would be to create an attribute on the view model . Something like:

[StringLength(50, ErrorMessage = "Phone Number can only be 50 characters.")]
public string PhoneNumber { get; set; }

If more than 50 characters are typed, this will produce an error with the model, which you can display client-side. If you'd prefer to not even allow them to enter more than 50 characters, then can utilize maxlength :

@Html.TextBoxFor(model => model.PhoneNumber, new {maxlength = 50}) 

Idea #1

Step 1) Query the database from the field information from the table in question.

Step 2) By System Types you can get the adjusted field length for each column.

Step 3) Write a function that matches the data returned with the data attempting to be passed (c#) and limit/truncate the data within the MVC application.

Step 4) Write the truncated data to the SQL server.


Idea #2 (Safer)

Send all database writes to a stored procedure that conditions the data prior to saving the transmitted data to the database. Reduces the risk of code injection, while giving you full control of any limitations inherent of the table you are writing to.

Sample code to get information on the table:

select 
   c.name, c.system_type_id,c.max_length,c.precision,c.scale 
 from 
   sys.columns as c 
   inner join sys.tables as t on c.object_id = t.object_id
where 
  t.name = 'SomeTable'

An easy solution is to add truncation to your setter

public string SomeString{
 get; 
 set { // In here put truncation code - this should fire when coming back from the view }; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM