Jack
Jack

Reputation: 1

MaskedTextBoxFor loses value after submitting the MVC Razor View

After submitting the form to the controller, the MaskedTextBoxFor inputs lose their values if the view returns from controller while all the other values (textboxdor, dropdownlistfor) remain as they are submitted. So, how to make MaskedTextBoxFor values remain when the submitted view returns from the controller? Thanks in advance...

View (update):

@model EurodeskMultipliers.Domain.Entities.Multiplier


@using (Html.BeginForm("Create", "Multiplier", FormMethod.Post,
new { id = "createForm", enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="container">

        <fieldset>
            <section>
                <div class="legend-left">                        

                    @Html.LabelFor(m => m.Phone)
                    @(Html.Kendo().MaskedTextBoxFor(m => m.Phone).Mask("(0999) 000 00 00"))
                    @Html.ValidationMessageFor(m => m.Phone)
                    <br />                       

                    @Html.LabelFor(m => m.ContactPhone)
                    @(Html.Kendo().MaskedTextBoxFor(m => m.ContactPhone).Mask("(0999) 000 00 00"))
                    <br />

                    @Html.LabelFor(m => m.ContactMobile)
                    @(Html.Kendo().MaskedTextBoxFor(m => m.ContactMobile).Mask("(0999) 000 00 00"))
                    @Html.ValidationMessageFor(m => m.ContactMobile)
                    <br />
                </div>
            </section>
        </fieldset>

        <div class="dv-right">
            @(Html.Kendo().Button()
                .Name("submitbtn")
                .Content("Save")
            )                
        </div>
    </div>
}


Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Multiplier multiplier)
{
    try
    {
        if (ModelState.IsValid)
        {
            return View(); //FOR TESTING "MaskedTextBox"

            db.Multipliers.Add(multiplier);
            db.SaveChanges();
            return RedirectToAction("Completed");
        }
    }
    catch (RetryLimitExceededException /* dex */)
        {
        //Log the error (uncomment dex variable name and add a line here to write a log.)
        ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
    }

    return View(multiplier);
}


Model:

public class Multiplier
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [RegularExpression(@"\([0-9]{4}\) [0-9]{3} [0-9]{2} [0-9]{2}", ErrorMessage = "Check phone number.")] 
    [MaxLength(20)]
    [Display(Name = "Phone")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Required")]
    [RegularExpression(@"\([0-9]{4}\) [0-9]{3} [0-9]{2} [0-9]{2}", ErrorMessage = "Check phone number.")] 
    [MaxLength(20)]
    [Display(Name = "Mobile Phone")]
    public string ContactMobile { get; set; } 

    //Navigation property       
    public virtual InstituteStatus InstituteStatus { get; set; }

    [ForeignKey("TermID")]
    public virtual Lookup Lookup { get; set; }

    //Collection navigation property
    public virtual ICollection<Participant> Participants { get; set; }

    //For using two Foreign Key on the same (Multiplier) table 
    [ForeignKey("MultiplierCityID")]
    [InverseProperty("MultiplierCityMultipliers")]
    public virtual City MultiplierCity { get; set; }

    [ForeignKey("ContactCityID")]
    [InverseProperty("ContactCityMultipliers")]
    public virtual City ContactCity { get; set; }
}

Upvotes: 1

Views: 3256

Answers (5)

Daniel Young
Daniel Young

Reputation: 436

I've been having this same problem with MaskTextBox, but lucky for me, I had encountered a similar problem with an unrelated issue. My maskedtextbox was for a Phone Number field, which I had placed in an editor template.

@model string
@(Html.Kendo()
    .MaskedTextBox()
    .Name(Html.IdForModel().ToString())
    .Mask("000-000-0000")            
    .Deferred())

With a previous issue, I solved it by looking into the modelstate for the model and seeing if it had an attemptedValue (from the failed validation). Then if it does I set it to the MaskedTextBox value option. The updated editor template is as below.

@model string
@{ 
    string attemptedValue = "";
    ModelState modelStateForValue = Html.ViewData.ModelState[Html.IdForModel().ToString()];
    if (modelStateForValue != null)
    {
        attemptedValue = modelStateForValue.Value.AttemptedValue;
    }
}
@(Html.Kendo()
    .MaskedTextBox()
    .Name(Html.IdForModel().ToString())
    .Mask("000-000-0000")    
    .Value((!string.IsNullOrEmpty(attemptedValue)) ? attemptedValue : "")
    .Deferred())

Hope this helps.

Upvotes: 0

Russell
Russell

Reputation: 21

I was having the same issue with one of my forms. It appears that the MaskedTextBoxFor razor extension is not looking at the values in ModelState. So if the validation fails and the form reloads, then part of the form will repopulate but the phone numbers will not.

So I simply used a normal @Html.TextBoxFor but added the kendo mask manually via javascript and it worked fine.

Upvotes: 1

Jack
Jack

Reputation: 1

Finally I see that using @Html.TextBoxFor() with class option "k-textbox" solved the problem and there might be a problem regarding to Html.Kendo().MaskedTextBox(). Because everyting is the same except from it and so, for those who might encounter the problem I posted the last status of the field below. On the other hand, many thanks to @jumpingcode, OnaBai and @mmillican for their kind help. I voted up their answers.

@Html.LabelFor(m => m.Phone)
@Html.TextBoxFor(m => m.Phone, new { maxlength = 13, @class = "k-textbox", placeholder = "+49xxxxxxxxxx" })
@Html.ValidationMessageFor(m => m.Phone)

Upvotes: 0

Matt Millican
Matt Millican

Reputation: 4054

In your Controller code snippet in your original question, you have the following line:

return View(); //FOR TESTING "MaskedTextBox"

The value is not binding to the MultiSelectFor() because you're not passing the model back to the view. If you change it to the following, it should work:

return View(multiplier);

Upvotes: 0

ediblecode
ediblecode

Reputation: 11971

If you look at the ASP.NET MVC example on Telerik here. You'll see that you are you using MaskedTextBoxFor rather than MaskedTextBox. Here is the example code from the site:

@(Html.Kendo().MaskedTextBox()
    .Name("phone_number")
    .Mask("(999) 000-0000")
    .Value("555 123 4567")
)

Here you want to replace .Name("phone_number") with .Name("Phone")

Upvotes: 1

Related Questions