How do I make a Html textbox to only take integer in Razor MVC?

18,898

Solution 1

You can do something like this:

@Html.TextBox('SearchString2', new { @type = "number" }) 

This should set the type to be a number, you could then use attributes on your model to help limit it to only ints like so:

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
public string SearchString2 { get; set; }

You'll need to replace the regex with an actual regex and put an validation message in.

Here's more info on validation: http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation

Solution 2

Actually, I think the correction needed to the above answer is

@Html.TextBox('SearchString2',null, new {@type="number"})

otherwise type=number shows up in the value.

Share:
18,898
Danieboy
Author by

Danieboy

http://danieboy.github.io/

Updated on June 25, 2022

Comments

  • Danieboy
    Danieboy almost 2 years

    Haven't been able to find a good answer to my situation yet. I want this textbox to only take numbers and still have the id "SearchString2" so I can use it in my controller. Any idea how?

    if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
    {
        @:<p><b>Customer ID:</b> @Html.TextBox("SearchString2")</p>
    }
    

    Thanks in advance.