简体   繁体   English

如何在MVC中使用html.textboxfor数字

[英]How to use html.textboxfor for numbers in MVC

I am developing MVC web app, having a model class student.cs 我正在开发MVC网络应用程序,并有一个class 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? 如何使用Html.TextBoxFor整数?

Create a new ASP.NET MVC project and use only the code you presented: 创建一个新的ASP.NET MVC项目,并仅使用您提供的代码:

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);
        }


    }

如果只需要最小值为1的数字,则可以这样操作: @Html.TextBoxFor(model => model.Id, new {@type = "number", @min = "1"})

You need to cast the integer to a string 您需要将整数转换为字符串

@Html.TextBoxFor(model => model.points.ToString()) @ Html.TextBoxFor(模型=> model.points.ToString())

Edit: The code should work. 编辑:该代码应该工作。 A very simple test 一个非常简单的测试

The model 该模型

public class Product
{
    public int Id { get; set; }
}

The controller 控制器

 public ActionResult Index()
 {              
    var model = new Product {Id = 10};
    return View(model);
 }

The view 风景

@Html.TextBoxFor(model => model.Id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM