In ASP.NET MVC, I wrote below code to give the textbox a initial value:
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140",
@class = "mustInputText noime w50",
maxlength = "8", @Value = "0",
rule = "InputOnlyNum" })
And the Html source is as follows:
<input Value="0" class="mustInputText noime w50" id="WEIGHT" maxlength="8"
name="WEIGHT" rule="InputOnlyNum" tabindex="140" type="text" value="" />
I notices that there are two Value attributes in the “input” tag:
Value="0" and value=""
How to make it only show one value attribute?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Use TextBox instead of TextBoxFor
@Html.TextBox("WEIGHT", Model.WEIGHT ?? "0", new {...})
or if WEIGHT is an empty string
@Html.TextBox("WEIGHT", Model.WEIGHT == "" ? "0" : Model.WEIGHT, new {...})
Method 2
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:
<input class="mustInputText noime w50"
id="WEIGHT"
maxlength="8"
name="WEIGHT"
rule="InputOnlyNum"
tabindex="140"
type="text"
value="0" />
Method 3
Well you’ve explicitly stated Value, not value.
Try:
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8", @value = "0", rule = "InputOnlyNum" })
Method 4
Untested, but try TextBox instead of TextBoxFor, as it has an overload for passing the value as the second parameter.
@Html.TextBox(p => p.WEIGHT, "0",
new { tabindex = "140", @class = "mustInputText noime w50",
maxlength = "8", @Value = "0", rule = "InputOnlyNum" })
The other option is to set defaults in the constructor of the model class that initializes WEIGHT.
Method 5
Maybe this? Untested.
@Html.TextBoxFor(p => (p.WEIGHT==null ? 0 : p.WEIGHT), new { tabindex = "140",
@class = "mustInputText noime w50",
maxlength = "8",
rule = "InputOnlyNum" })
Method 6
@Html.TextBoxFor(p => p.WEIGHT, new { tabindex = "140", @class = "mustInputText noime w50", maxlength = "8",
@value = model.WEIGHT==null?"0":model.WEIGHT, rule = "InputOnlyNum" })
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0