代码之家  ›  专栏  ›  技术社区  ›  Anders

部分ASP.NETMVC应用程序数据保存未应用

  •  0
  • Anders  · 技术社区  · 14 年前

    我正在写一个MVC应用程序,我想做一些额外的格式化,使所有的电话号码都存储在同一个。为此,我创建了一个简单的外部函数来剥离所有非数字字符并返回格式化字符串:

    public static string FormatPhone(string phone)
    {
        string[] temp = { "", "", "" };
    
        phone = Regex.Replace(phone, "[^0-9]","");
    
        temp[0] = phone.Substring(0, 3);
        temp[1] = phone.Substring(3, 3);
        temp[2] = phone.Substring(6);
    
        return string.Format("({0}) {1}-{2}", temp[0], temp[1], temp[2]);
    }
    

    [Required(ErrorMessage = "Phone Number is required.")]
    [DisplayName("Phone Number:")]
    [StringLength(16)]
    [RegularExpression("^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
     ErrorMessage = "Please enter a valid phone number.")]
    public object phone { get; set; }
    

    [HttpPost]
    public ActionResult Edit(int id, FormCollection collection)
    {
        var customer = customerDB.Customers.Single(c => c.id == id);
    
        try
        {
            customer.phone = HelperFunctions.FormatPhone(customer.phone);    
            UpdateModel(customer,"customer");                 
            customerDB.SaveChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            var viewModel = new CustomerManagerViewModel
            {
                customer = customerDB.Customers.Single(c => c.id == id)
            };
            return View(viewModel);
        }
    }
    

    当我逐步执行此操作时,字符串会更新,然后重置回在运行函数之前的格式。另外,任何其他字段更新都没有问题。

    有什么想法吗?提前谢谢。

    1 回复  |  直到 10 年前
        1
  •  2
  •   Robert Harvey    14 年前

    你的 UpdateModel customer 现场。尝试交换这两行代码:

    try 
    { 
        UpdateModel(customer,"customer");                          <--              
        customer.phone = HelperFunctions.FormatPhone(customer.phone);  <--   
        customerDB.SaveChanges(); 
        return RedirectToAction("Index"); 
    }