在ASP中TextBoxFor的默认值.净MVC

本文关键字:默认值 MVC TextBoxFor ASP | 更新日期: 2023-09-27 18:12:37

. NET MVC,我写了下面的代码给文本框一个初始值:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
                                      @class = "mustInputText noime  w50", 
                                      maxlength = "8", @Value = "0", 
                                      rule = "InputOnlyNum" })

, Html源代码如下:

<input Value="0" class="mustInputText noime  w50" id="WEIGHT" maxlength="8" 
    name="WEIGHT" rule="InputOnlyNum" tabindex="140" type="text" value="" />

我注意到在"input"标签中有两个Value属性:Value="0"value=""

如何使它只显示一个值属性?

在ASP中TextBoxFor的默认值.净MVC

使用TextBox代替TextBoxFor

@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...})

或者如果WEIGHT是空字符串

@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...})

这似乎是默认行为。如果您真的想要避免双值属性,最好遵循更简洁的方法,即在控制器类的create方法中设置默认值。这遵循了MVC模式的思想。

//GET
public ActionResult CreateNewEntity()
{
    YourEntity newEntity= new YourEntity ();
    newEntity.WEIGHT= 0;
    return View(newEntity);
}

那么在你的视图中,你就不再需要使用value属性了:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", 
                                      @class = "mustInputText noime  w50",     
                                      maxlength = "8", 
                                      rule = "InputOnlyNum" })

生成的html是:

<input class="mustInputText noime  w50" 
       id="WEIGHT" 
       maxlength="8" 
       name="WEIGHT" 
       rule="InputOnlyNum" 
       tabindex="140" 
       type="text" 
       value="0" />

你明明说的是Value,不是value

试题:

 @Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime  w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" })

未测试,但尝试TextBox代替TextBoxFor,因为它有一个过载传递值作为第二个参数

@Html.TextBox(p => p.WEIGHT, "0",
    new { tabindex = "140", @class = "mustInputText noime  w50", 
          maxlength = "8", @Value = "0", rule = "InputOnlyNum" })
另一个选择是在初始化WEIGHT的模型类的构造函数中设置默认值。

也许是这个?测试。

@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140", 
      @class = "mustInputText noime  w50", 
      maxlength = "8",  
      rule = "InputOnlyNum" })
   @Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime  w50", maxlength = "8",
 @value =  model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" })