Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

razor - unable to apply Bootstrap classes to my EditorFor

I am working on an asp.net mvc-5 web application , and i wrote the following :-

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
&
@Html.EditorFor(model => model.Name, new { @class = "form-control"  })

but this will not have any effect on the generated html, but if i changed the EditorFor to be TextboxFor i will get the effect for the form-control class ? can anyone advice on this please ? i read that this is supported only inside asp.net mvc 5.1 ? so what are the available approaches i can follow to get this working other than upgrading my asp.net mvc-5 to asp.net mvc 5.1 , to eliminate the risk of upgrading? Can anyone adivce ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, to pass html attributes to a standard EditorFor() you need MVC-5.1+. If you want to replicate this with MVC-5, you can create a custom editor template and pass the attributes using the overload that accepts additionViewData. For example, create a new EditorTemplate named "String.cshtml" to apply the template for all properties that are typeof string

/Views/Shared/EditorTemplates/String.cshtml

@Html.TextBoxFor(m => m, ViewData["attributes"])

and in the view

@Html.EditorFor(m => m.Name, new { attributes = new { @class = "form-control" } })

or create a specificEditorTemplate

/Views/Shared/EditorTemplates/MyCustomTemplate.cshtml

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData["htmlAttributes"])

and in the view

@Html.EditorFor(m => m.Name, "MyCustomTemplate", new { attributes = new { @class = "form-control" } })

The second example shows how to respect the DisplayFormat attribute as mentioned in your comments above, for example

[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }

will format the value as a currency string.

This answer also gives some other options including creating a custom html helper for rendering bootstrap controls


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...