Default value for TextBoxFor in ASP.NET MVC

前端 未结 6 1720
我寻月下人不归
我寻月下人不归 2021-01-13 09:04

In ASP.NET MVC, I wrote below code to give the textbox a initial value:

@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = \"140\", 
                                


        
6条回答
  •  既然无缘
    2021-01-13 09:37

    It seems to be the default behavior. If you really want to avoid the double Value attributes, it's better to follow the cleaner way by setting the default value in the create method of the controller class. This follows the ideology of the MVC pattern.

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

    Then on your view, you won't need to use the value attribute anymore:

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

    Your resulting html is:

    
    

提交回复
热议问题