EditorFor() 및 html 속성
-
06-07-2019 - |
문제
Asp.Net MVC 2.0 미리보기 빌드는 다음과 같은 도우미를 제공합니다.
Html.EditorFor(c => c.propertyname)
속성 이름이 문자열인 경우 위 코드는 텍스트 상자를 렌더링합니다.
MaxLength 및 Size 속성을 텍스트 상자나 자체 CSS 클래스 속성에 전달하려면 어떻게 해야 합니까?
내 신청서의 각 크기와 길이 조합에 대해 하나의 템플릿을 만들어야 합니까?그렇다면 기본 템플릿을 사용할 수 없게 됩니다.
해결책 11
나는 내 자신의 질문에 대답하기 위해 블로그 항목을 썼습니다.
다른 팁
MVC3에서는 다음과 같이 너비를 설정할 수 있습니다.
@Html.TextBoxFor(c => c.PropertyName, new { style = "width: 500px;" })
my/views/shared/editortemplates 폴더에서 string.ascx라는 editortemplate을 만들어 이것을 해결했습니다.
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
int maxLength = 100;
if (ViewData["size"] != null)
{
size = (int)ViewData["size"];
}
if (ViewData["maxLength"] != null)
{
maxLength = (int)ViewData["maxLength"];
}
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>
내 견해로는 사용합니다
<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>
나를위한 매력처럼 작동합니다!
@html.editorfor에 대한 HTML 속성을 설정할 때이 스레드 또는 다른 스레드의 답은 나에게 큰 도움이되지 않았습니다. 그러나 나는 큰 대답을 찾았습니다
나는 같은 접근법을 사용했고 많은 추가 코드를 쓰지 않고 아름답게 작동했습니다. html.editorfor의 html 출력의 ID 속성이 설정되어 있습니다. 보기 코드
<style type="text/css">
#dob
{
width:6em;
}
</style>
@using (Html.BeginForm())
{
Enter date:
@Html.EditorFor(m => m.DateOfBirth, null, "dob", null)
}
"DD MMM YYYY"로 데이터 주석 및 날짜 서식이있는 모델 속성
[Required(ErrorMessage= "Date of birth is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateOfBirth { get; set; }
추가 코드를 많이 쓰지 않고 매력처럼 일했습니다. 이 답변은 ASP.NET MVC 3 Razor C#을 사용합니다.
보고 싶을 수도 있습니다 Kiran Chand의 블로그 게시물, 그는 다음과 같은보기 모델에서 사용자 정의 메타 데이터를 사용합니다.
[HtmlProperties(Size = 5, MaxLength = 10)]
public string Title { get; set; }
이것은 메타 데이터를 사용하는 사용자 정의 템플릿과 결합됩니다. 내 의견으로는 깨끗하고 간단한 접근 방식이지만이 공통 사용 사례가 MVC에 내장 된 것을보고 싶습니다.
"추가 뷰드타"에 그것을 전달하고 반대편에서 읽은 사람은 아무도 놀랐습니다.
보다 (명확성을 위해 라인 브레이크와 함께) :
<%= Html.EditorFor(c => c.propertyname, new
{
htmlAttributes = new
{
@class = "myClass"
}
}
)%>
편집기 템플릿 :
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.TextBox("", Model, ViewData["htmlAttributes"])) %>
문제는 템플릿에 여러 HTML 요소를 포함 할 수 있으므로 MVC는 크기/클래스를 적용 할 수있는 요소를 알지 못합니다. 직접 정의해야합니다.
TextBoxViewModel이라는 자신의 클래스에서 템플릿을 파생 시키십시오.
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
}
public string GetAttributesString()
{
return string.Join(" ", moreAttributes.Select(x => x.Key + "='" + x.Value + "'").ToArray()); // don't forget to encode
}
}
템플릿에서는 다음을 수행 할 수 있습니다.
<input value="<%= Model.Value %>" <%= Model.GetAttributesString() %> />
당신의 관점에서 당신은 다음과 같습니다.
<%= Html.EditorFor(x => x.StringValue) %>
or
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue, new IDictionary<string, object> { {'class', 'myclass'}, {'size', 15}}) %>
첫 번째 양식은 문자열의 기본 템플릿을 렌더링합니다. 두 번째 양식은 사용자 정의 템플릿을 렌더링합니다.
대체 구문 사용 유창한 인터페이스 사용 :
public class TextBoxViewModel
{
public string Value { get; set; }
IDictionary<string, object> moreAttributes;
public TextBoxViewModel(string value, IDictionary<string, object> moreAttributes)
{
// set class properties here
moreAttributes = new Dictionary<string, object>();
}
public TextBoxViewModel Attr(string name, object value)
{
moreAttributes[name] = value;
return this;
}
}
// and in the view
<%= Html.EditorFor(x => new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) %>
보기 에서이 작업을 수행하는 대신 컨트롤러에서도이를 수행하거나 뷰 모델에서 훨씬 더 나을 수도 있습니다.
public ActionResult Action()
{
// now you can Html.EditorFor(x => x.StringValue) and it will pick attributes
return View(new { StringValue = new TextBoxViewModel(x.StringValue).Attr("class", "myclass").Attr("size", 15) });
}
또한 기본 템플릿 ViewModel 클래스 (모든 뷰 템플릿의 공통 근거)를 만들 수 있습니다. 여기에는 속성 등에 대한 기본 지원이 포함됩니다.
그러나 일반적으로 MVC V2는 더 나은 솔루션이 필요하다고 생각합니다. 여전히 베타입니다 - 가서 요청하십시오 ;-)
CSS를 사용하는 것이 갈 길이라고 생각합니다. XAML과 같이 .NET 코딩으로 더 많은 일을 할 수 있기를 바랍니다. 그러나 브라우저에서 CSS는 King입니다.
site.css
#account-note-input {
width:1000px;
height:100px;
}
.cshtml
<div class="editor-label">
@Html.LabelFor(model => model.Note)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Note, null, "account-note-input", null)
@Html.ValidationMessageFor(model => model.Note)
</div>
조
MVC 5에서와 마찬가지로 속성을 추가하려면 간단히 할 수 있습니다.
@Html.EditorFor(m => m.Name, new { htmlAttributes = new { @required = "true", @anotherAttribute = "whatever" } })
발견 된 정보 이 블로그
속성에 대한 속성을 정의 할 수 있습니다.
[StringLength(100)]
public string Body { get; set; }
이것은 다음과 같습니다 System.ComponentModel.DataAnnotations
. 당신이 찾을 수 없다면 ValidationAttribute
당신이 필요하다는 것은 모든 사람이 사용자 정의 속성을 정의 할 수 있습니다.
안부, 카를로스
이것은 가장 매끄러운 솔루션은 아니지만 간단합니다. htmlhelper.editorfor 클래스에 연장을 쓸 수 있습니다. 이 확장에서는 도우미의 뷰 데이터에 옵션을 작성하는 옵션 매개 변수를 제공 할 수 있습니다. 코드는 다음과 같습니다.
첫째, 확장 방법 :
public static MvcHtmlString EditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, TemplateOptions options)
{
return helper.EditorFor(expression, options.TemplateName, new
{
cssClass = options.CssClass
});
}
다음으로 옵션 개체 :
public class TemplateOptions
{
public string TemplateName { get; set; }
public string CssClass { get; set; }
// other properties for info you'd like to pass to your templates,
// and by using an options object, you avoid method overload bloat.
}
마지막으로 String.ascx 템플릿의 줄이 있습니다.
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = ViewData["cssClass"] ?? "" }) %>
솔직히, 나는 이것이 당신의 코드를 길 아래로 유지 해야하는 가난한 영혼에게 간단하고 분명하다고 생각합니다. 또한 템플릿으로 전달하려는 다양한 다른 정보에 대해 쉽게 확장 할 수 있습니다. 주변 HTML, LA를 표준화하는 데 도움이되는 템플릿 세트에서 가능한 한 많이 포장하려는 프로젝트에서 지금까지 잘 작동합니다. http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-5-master-page-templates.html.
왜 그것이 html.editorfor에서 작동하지 않는지 모르겠지만 TextBoxfor를 시도해 보았습니다.
@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})
... 그리고 또한 검증이 작동합니다.
내 연습에서 나는 대부분의 경우 텍스트 상자에 하나의 htmlhelper 만있는 editortemplates를 사용하는 것이 가장 좋다는 것을 알았습니다. 더 복잡한 HTML 구조를위한 템플릿을 원한다면 별도의 HTMLHELPER를 작성하겠습니다.
텍스트 상자의 htmlattributes 대신에 전체 ViewData 객체를 붙일 수 있다는 점을 감안할 때. 또한 특별 대우가 필요한 경우 ViewData의 일부 속성에 대한 사용자 정의 코드를 작성할 수 있습니다.
@model DateTime?
@*
1) applies class datepicker to the input;
2) applies additionalViewData object to the attributes of the input
3) applies property "format" to the format of the input date.
*@
@{
if (ViewData["class"] != null) { ViewData["class"] += " datepicker"; }
else { ViewData["class"] = " datepicker"; }
string format = "MM/dd/yyyy";
if (ViewData["format"] != null)
{
format = ViewData["format"].ToString();
ViewData.Remove("format");
}
}
@Html.TextBox("", (Model.HasValue ? Model.Value.ToString(format) : string.Empty), ViewData)
아래는보기의 구문과 출력 HTML의 예입니다.
@Html.EditorFor(m => m.Date)
<input class="datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="01/08/2012">
@Html.EditorFor(m => m.Date, new { @class = "myClass", @format = "M/dd" })
<input class="myClass datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="1/08">
왜냐하면 질문은 EditorFor TextBoxFor WEFX의 제안이 작동하지 않습니다.
개별 입력 상자를 변경하려면 EditorFor 메서드의 출력을 처리하면 됩니다.
<%: new HtmlString(Html.EditorFor(m=>m.propertyname).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line my500pxWideClass\"")) %>
MVC가 EditorFor 텍스트 상자의 클래스를 다음과 같이 설정하므로 모든 EditorFor를 변경할 수도 있습니다. .텍스트 상자, 이므로 스타일시트나 페이지에서 이 스타일을 재정의할 수 있습니다.
.text-box {
width: 80em;
}
또한 다음 스타일을 설정할 수도 있습니다.
input[type="text"] {
width: 200px;
}
- 이는 .text-box를 재정의하고 EditorFor 등 모든 입력 텍스트 상자를 변경합니다.
또한 MVC3에서 TextBox의 너비를 설정하는 데 문제가 있었으며 CLSS 속성을 TextArea Control에서 작동했지만 TextBoxfor Control 또는 Editor for Control에는 작동하지 않습니다.
나는 팔로우를 시도했고 그것은 나를 위해 일했다 :
@html.textboxfor (model => model.title, new {class = "textbox", style = "width : 90%;"})
또한이 경우 유효성 검사가 완벽하게 작동합니다.
당신이 그것을 돌릴 수있는 한 가지 방법은보기 모델에 대표가 이와 같은 특수 렌더링 인쇄를 처리하는 것입니다. 페이징 클래스를 위해이 작업을 수행했는데 모델에 공공 재산을 노출시킵니다. Func<int, string> RenderUrl
그것을 다루기 위해.
따라서 사용자 정의 비트가 작성되는 방법을 정의하십시오.
Model.Paging.RenderUrl = (page) => { return string.Concat(@"/foo/", page); };
뷰를 출력하십시오 Paging
수업:
@Html.DisplayFor(m => m.Paging)
... 그리고 실제 Paging
보다:
@model Paging
@if (Model.Pages > 1)
{
<ul class="paging">
@for (int page = 1; page <= Model.Pages; page++)
{
<li><a href="@Model.RenderUrl(page)">@page</a></li>
}
</ul>
}
그것은 과도하게 복잡한 문제로 보일 수 있지만, 나는이 호출기를 어디에나 사용하고 동일한 보일러 플레이트 코드를 볼 수 없었습니다.
업데이트 : HM, 분명히 모델은 값으로 전달되므로 속성이 보존되지 않기 때문에 작동하지 않습니다. 그러나 나는이 답을 아이디어로 남겨 둡니다.
또 다른 솔루션은 모델에서 자신의 속성을 확인할 자신의 텍스트 상자/etc helpers를 추가하는 것입니다.
public class ViewModel
{
[MyAddAttribute("class", "myclass")]
public string StringValue { get; set; }
}
public class MyExtensions
{
public static IDictionary<string, object> GetMyAttributes(object model)
{
// kind of prototype code...
return model.GetType().GetCustomAttributes(typeof(MyAddAttribute)).OfType<MyAddAttribute>().ToDictionary(
x => x.Name, x => x.Value);
}
}
<!-- in the template -->
<%= Html.TextBox("Name", Model, MyExtensions.GetMyAttributes(Model)) %>
이것은 더 쉽지만 편리하고 유연하지는 않습니다.
이것은 여기에서 솔루션을 얻는 가장 깨끗하고 우아하고 간단한 방법입니다.
화려한 블로그 게시물과 미친 교수와 같은 맞춤형 확장/도우미 방법을 작성하는 데 지저분한 과잉.
http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx
/views/shared/editortemplates 폴더에서 string.ascx라는 editortemplate을 사용하는 @tjeerdans 답변을 정말 좋아했습니다. 이 질문에 대한 가장 간단한 답변 인 것 같습니다. 그러나 Razor 구문을 사용하여 템플릿을 원했습니다. 또한 MVC3은 문자열 템플릿을 기본값으로 사용하는 것 같습니다 (StackoverFlow 질문 참조.문자열 용 MVC 디스플레이 템플릿은 정수에 사용됩니다") 따라서 모델을 문자열보다는 객체로 설정해야합니다. 내 템플릿은 지금까지 작동하는 것 같습니다.
@model object
@{ int size = 10; int maxLength = 100; }
@if (ViewData["size"] != null) {
Int32.TryParse((string)ViewData["size"], out size);
}
@if (ViewData["maxLength"] != null) {
Int32.TryParse((string)ViewData["maxLength"], out maxLength);
}
@Html.TextBox("", Model, new { Size = size, MaxLength = maxLength})
나는 그것을 해결했다 !!
면도기의 경우 구문은 다음과 같습니다.
@Html.TextAreaFor(m=>m.Address, new { style="Width:174px" })
이것은 텍스트 영역 너비를 스타일 매개 변수에서 정의한 너비로 조정합니다.
ASPX의 경우 구문은 다음과 같습니다.
<%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15", style="Width:174px" })%>
이것은 트릭을 할 것입니다