1

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; }
}
Jack
  • 1
  • 21
  • 118
  • 236
  • 1
    After submitting the form, is the page being reloaded? – OnaBai Feb 23 '15 at 10:24
  • Of course. The situation like that: I fill in the input fields and submit the Razor View to the controller. Then, if there is a problem the view returns with the inputs and their data except from MaskedTextBoxFor. So, the user need to re-type all the telephone fields again due to this problem. I think there is similar problem related to Dropdownlist, but my problem is only related to MaskedTextBoxFor. Could you help pls? – Jack Feb 23 '15 at 10:42
  • 1
    I've seen this same effect when the value that I've assigned was not matching the mask then Kendo simply does not show the value. As far as I understand this cannot be happening in your case since you have initially assign one value, then send to the controller and the controller is returning the same value for review to the user (is this last assumption correct?) – OnaBai Feb 23 '15 at 11:47
  • @OnaBai: Actually I would prefer not assign any value during the first initialization. The user enter his/her phone number and then submit the form to the controller. So, may it cause the problem? – Jack Feb 23 '15 at 12:14
  • What I mean is that when it cames back from the server and "looses its value", is that value correct, isn't it? if you assign that same value in the initialization, does it get displayed? – OnaBai Feb 23 '15 at 12:16
  • Yes, when I use value property and set it on the View the value remains after postback while the other values entered before form submit disappears. – Jack Feb 23 '15 at 12:23
  • @OnaBai Any idea regarding to the problem? – Jack Feb 23 '15 at 13:05
  • @OnaBai Thanks, I solved the problem. Please check and mark as answer if you think it is ok. – Jack Feb 25 '15 at 10:21

5 Answers5

1

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")

ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • I tried also with MaskedTextBox() instead of MaskedTextBoxFor(). But it did not make any sense and still the telephove values lose after postback :( – Jack Feb 23 '15 at 11:08
  • 1
    @H.Johnson I tested myself locally and it works using `MaskedTextBox` rather than `MaskedTextBoxFor` – ediblecode Feb 23 '15 at 11:09
  • Thanks for your help. Could you please inform me how to test it on controller? Actually I use return(view) before saving the record in order to postback to the view? How should I test it? – Jack Feb 23 '15 at 11:11
  • @H.Johnson Please include your controller methods in the question – ediblecode Feb 23 '15 at 11:12
  • @H.Johnson And your `Multiplier` view model as well as your full form in the view. – ediblecode Feb 23 '15 at 11:17
  • I updated view code. However, this Create method does not use ViewModel, it directly calls Model as posted above. Is it ok? Thanks. – Jack Feb 23 '15 at 12:05
  • Any idea regarding to the problem? – Jack Feb 23 '15 at 13:05
1

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.

Russell
  • 21
  • 4
0

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);
Matt Millican
  • 4,044
  • 4
  • 38
  • 55
  • Yes, I am aware of this. But before adding this test line, the result was already the same. On the other hand, how can I test the postback on the controller as causing the view from controller before save action? – Jack Feb 23 '15 at 14:52
  • I don't understand your 2nd question in your comment - about testing the post back on the controller as causing the view? – Matt Millican Feb 23 '15 at 14:56
  • I meant that: In some case the view return from controller after postback it i.e. post a create form. How can I make the program act as like that? I tried to use return view(model) before the save action in my controller. Is there a more logical way? – Jack Feb 23 '15 at 15:43
0

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)
Jack
  • 1
  • 21
  • 118
  • 236
0

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.

Daniel Young
  • 436
  • 1
  • 3
  • 6