【问题标题】:How to use html.textboxfor for numbers in MVC如何在 MVC 中将 html.textboxfor 用于数字
【发布时间】:2016-04-14 15:06:15
【问题描述】:

我正在开发 MVC 网络应用程序,有一个模型类 student.cs

具有属性名称、地址、点,其中点是整数。鉴于我正在尝试使用:

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

编译器无法接受。 如何将 Html.TextBoxFor 用于整数?

【问题讨论】:

  • 你得到什么错误?
  • System.FormatException:输入字符串的格式不正确。当我尝试转换它时,BANGG –
  • 可以展示模型类吗?
  • public class Student { public Student() { } //构造函数:) public Student(int ID, int repPoints) { this.ID = ID; this.repPoints = repPoints; } 公共 int ID { 获取;放; } 公共 int repPoints { 获取;放; } }
  • 我还有很多其他属性

标签: c# html asp.net-mvc


【解决方案1】:

创建一个新的 ASP.NET MVC 项目并仅使用您提供的代码:

你会看到它有效。

查看

<%@ 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>

型号

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

控制器

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


    }

【讨论】:

  • 这可行,但实际上我不想将 ID 设置为 10 也不将 repPoints 设置为 20,我要做的就是动态设置它们,以便从视图中获取 repPoints 值
  • 查看更改后的控制器。您可以将表单发布到 UpdateStudent 并且学生将拥有用户输入的值
【解决方案2】:

如果你只想要最小值为 1 的数字,你可以这样做:@Html.TextBoxFor(model =&gt; model.Id, new {@type = "number", @min = "1"})

【讨论】:

    【解决方案3】:

    您需要将整数转换为字符串

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

    编辑: 代码应该可以工作。一个非常简单的测试

    型号

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

    控制器

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

    景色

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

    【讨论】:

    • 然后它说:无效操作异常//模板只能与字段访问、属性访问、单维数组索引或单参数自定义索引器表达式一起使用。
    • System.FormatException:输入字符串的格式不正确。当我尝试转换它时,BANGG
    • 在Visual Studio中留个心眼,看看model.points的值是多少
    • 在模型类中,points 是一个属性,我使用: Convert.ToString(s.repPoints)) 仍然,错误消息:System.InvalidOperationException : 模板只能与字段访问、属性访问、一维数组索引或单参数自定义索引器表达式一起使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2017-10-16
    相关资源
    最近更新 更多