简体   繁体   English

在保存到数据库表之前,如何截断从UI控件获取的多余字符串字符?

[英]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. 我有一个MVC应用程序,其中从文本框控件接收一些数据作为电话号码。 In the database table i have specified it's column size to (varchar 50). 在数据库表中,我已将其列大小指定为(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. 因此,如果我在数据库系统中插入了50个以上的字符,则会引发如下错误:对一个或多个实体的验证失败。 See 'EntityValidationErrors' property for more details. 有关更多详细信息,请参见'EntityValidationErrors'属性。

So i want to truncate all the extra character before saving it into database automatically without restricting its size on the UI control itself. 所以我想截断所有多余的字符,然后将其自动保存到数据库中,而又不限制它在UI控件本身上的大小。

Below is the code when it try to save it into database using EF: 下面是尝试使用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 . 由于您使用的是MVC ,另一个选择是在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. 如果键入的字符超过50个,则会在模型上产生错误,您可以在客户端显示该错误。 If you'd prefer to not even allow them to enter more than 50 characters, then can utilize maxlength : 如果您甚至不想允许他们输入超过50个字符,则可以利用maxlength

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

Idea #1 想法#1

Step 1) Query the database from the field information from the table in question. 步骤1)从有关表的字段信息中查询数据库。

Step 2) By System Types you can get the adjusted field length for each column. 步骤2)通过“系统类型”,您可以获取每列的调整字段长度。

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. 步骤3)编写一个函数,将返回的数据与尝试传递的数据(c#)匹配,并在MVC应用程序中限制/截断数据。

Step 4) Write the truncated data to the SQL server. 步骤4)将截断的数据写入SQL Server。


Idea #2 (Safer) 想法2(更安全)

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 }; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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