开发者

Part of ASP.NET MVC application data save not being applied

开发者 https://www.devze.com 2023-01-15 19:16 出处:网络
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 ch

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 charact开发者_如何学运维ers 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 advance.


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"); 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消