C# 如何为 Html.TextBoxFor( ... ) 文本框设置默认值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10485402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:01:28  来源:igfitidea点击:

How do you set a default value for a Html.TextBoxFor( ... ) text box?

c#asp.net-mvctextbox

提问by Alex

I know that you can create a textbox using ASP.NET that will automatically be filled with whatever the value in the model is by using

我知道您可以使用 ASP.NET 创建一个文本框,该文本框将通过使用模型中的任何值自动填充

<%: Html.TextBoxFor(model => model.FirstName, new { id = "FirstName", placeholder = "[First Name]" }) %>

Is there a way to give it a default value if model.FirstNameis null?

如果model.FirstName为空,有没有办法给它一个默认值?

I've tried adding a value attribute, but that didn't work.

我试过添加一个 value 属性,但这没有用。

I also can't pass in a model with that value included, because it will affect other areas of the form.

我也无法传入包含该值的模型,因为它会影响表单的其他区域。

采纳答案by Mario Sannum

You could change the model property to return a default value if it's null (or setting default values when creating the model) or you can use the Html.TextBoxhelper instead of Html.TextBoxFor:

如果模型属性为 null(或在创建模型时设置默认值),您可以更改模型属性以返回默认值,或者您可以使用Html.TextBox帮助程序而不是Html.TextBoxFor

<%: Html.TextBox("FirstName", Model.FirstName ?? "The default value", new { id = "FirstName", placeholder = "[First Name]" }) %>

or use the value-attribute:

或使用值属性:

<%: Html.TextBoxFor(model => model.FirstName, new { @Value = "The default value", id = "FirstName", placeholder = "[First Name]" }) %>

回答by chris

Would something like a watermark work for what you're trying to accomplish?

像水印这样的东西是否适合您要完成的任务?

There are a number of different implementation for jquery - thislooks like it would work, and there is an option to use the title attribute for the watermark, which could be part of your model.

jquery 有许多不同的实现 -看起来可以工作,并且有一个选项可以使用水印的标题属性,这可能是您模型的一部分。