Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use html.textboxfor for numbers in MVC

I am developing MVC web app, having a model class student.cs

which has properties name, address, points where points is an integer. in view I am trying to use:

<%=Html.TextBoxFor(model => model.points) %>

The compiler cannot accept it. how to use Html.TextBoxFor for integers?

like image 356
Samer_Azar Avatar asked Oct 30 '25 09:10

Samer_Azar


2 Answers

If you only want numbers with minimum value 1 you can do it like this: @Html.TextBoxFor(model => model.Id, new {@type = "number", @min = "1"})

like image 175
Ogglas Avatar answered Nov 02 '25 00:11

Ogglas


Create a new ASP.NET MVC project and use only the code you presented:

you will see that it works.

View

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Models.Student>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <%= Html.TextBoxFor(model => model.repPoints) %>
    </div>
</body>
</html>

Model

public class Student 
{ 
public Student() { } //constructor :) 

public Student(int ID, int repPoints) 

{ this.ID = ID; this.repPoints = repPoints; } 

public int ID { get; set; } 

public int repPoints { get; set; } }

Controller

 public class TestController : Controller
    {
        public ActionResult Index()
        {
            Student student = new Student(10, 20);

            return View(student);
        }

        public ActionResult UpdateStudent(Student student)
        {
            //access the DB here

            return View("Index",student);
        }


    }
like image 37
Mathias F Avatar answered Nov 02 '25 01:11

Mathias F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!