views:

13

answers:

1

Hello SO:

I am writing an MVC application, and I wanted to do some extra formatting so the phone numbers all are stored the same. To accomplish this I made a simple external function to strip all non-numeric characters and return the formatted string:

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

There is also regex in place in the model to make sure the entered phone number is a valid one:

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

This is what I did in the controller:

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

When I step through this, the string updates then resets back to the format it was before being ran through the function. Also, any of the other fields update with no problem.

Any ideas? Thanks in advanced.

+2  A: 

Your UpdateModel call is overwriting the customer field. Try swapping these two lines of code:

try 
{ 
    UpdateModel(customer,"customer");                          <--              
    customer.phone = HelperFunctions.FormatPhone(customer.phone);  <--   
    customerDB.SaveChanges(); 
    return RedirectToAction("Index"); 
} 
Robert Harvey
I retract my last comment, I accidentally pasted the wrong code. Updated to this and it works fine. I could have sworn I tried this before posting up here, thanks for catching it though!
Anders