Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 494
Danieboy Avatar asked Dec 24 '22 13:12

Danieboy


2 Answers

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

like image 152
Blake Avatar answered Dec 27 '22 03:12

Blake


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.

like image 39
D Owens Avatar answered Dec 27 '22 05:12

D Owens