EditorFor () 및 html 속성
Asp.Net MVC 2.0 미리보기 빌드는 다음과 같은 도우미를 제공합니다.
Html.EditorFor(c => c.propertyname)
속성 이름이 문자열 인 경우 위 코드는 texbox를 렌더링합니다.
MaxLength 및 Size 속성을 텍스트 상자 또는 내 CSS 클래스 속성에 전달하려면 어떻게합니까?
응용 프로그램에서 각 크기 및 길이 조합마다 하나의 템플릿을 만들어야합니까? 그렇다면 사용 가능한 기본 템플릿이 아닙니다.
MVC3에서는 다음과 같이 너비를 설정할 수 있습니다.
@Html.TextBoxFor(c => c.PropertyName, new { style = "width: 500px;" })
내 / 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 속성 설정에 대한 this 또는 다른 스레드의 답변은 나에게 큰 도움이되지 않았습니다. 그러나 나는 큰 대답을 찾았다.
나는 동일한 접근 방식을 사용했으며 많은 추가 코드를 작성하지 않고도 아름답게 작동했습니다. 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에 내장 된이 일반적인 사용 사례를보고 싶습니다.
"additionalViewData"에 전달하고 다른 쪽에서 읽는 것에 대해 언급 한 사람이 아무도 없습니다.
보기 (명확하게하기 위해 줄 바꿈) :
<%= 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) %>
뷰 에서이 작업을 수행하는 대신 컨트롤러에서 또는 ViewModel 에서이 작업을 수행하는 것이 좋습니다.
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) });
}
또한 속성 / 기타에 대한 기본 지원을 포함 할 기본 TemplateViewModel 클래스 (모든 뷰 템플릿의 공통 근거)를 만들 수 있습니다.
그러나 일반적으로 MVC v2에는 더 나은 솔루션이 필요하다고 생각합니다. 여전히 베타입니다-요청하십시오 ;-)
CSS를 사용하는 것이 좋습니다. XAML과 같이 .NET 코딩으로 더 많은 것을 할 수 있기를 원하지만 브라우저 CSS는 왕입니다.
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 클래스에 대한 확장을 작성할 수 있습니다. 이 확장에서는 도우미의 ViewData에 옵션을 쓰는 옵션 매개 변수를 제공 할 수 있습니다. 코드는 다음과 같습니다.
먼저 확장 방법 :
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"] ?? "" }) %>
Frankly, I think this is straightforward and clear to the poor soul who has to maintain your code down the road. And it is easy to extend for various other bits of info you'd like to pass to your templates. It's working well so far for me in a project where I'm trying to wrap as much as I can in a set of template to help standardize the surrounding html, a la http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-5-master-page-templates.html.
I wrote a blog entry to answer my own question
Adding html attributes support for Templates - ASP.Net MVC 2.0 Beta
I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.
@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})
...and also validation works.
In my practice I found that it is best to use EditorTemplates with only one HtmlHelper in it - TextBox that is in most cases. If I want a template for more complex html structure, I'll write a separate HtmlHelper.
Given that we can stick the whole ViewData object in place of htmlAttributes of the TextBox. In addition we can write some customization code for some of the properties of the ViewData if they need special treatment:
@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)
Below are the examples of the syntax in the view and the outputted 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">
Because the question is for EditorFor not TextBoxFor WEFX's suggestion doesn't work.
For changing individual input boxes, you can process the output of the EditorFor method:
<%: new HtmlString(Html.EditorFor(m=>m.propertyname).ToString().Replace("class=\"text-box single-line\"", "class=\"text-box single-line my500pxWideClass\"")) %>
It is also possible to change ALL your EditorFors as it turns out MVC sets the class of EditorFor text boxes with .text-box, therefore you can just override this style, in your stylesheet or on the page.
.text-box {
width: 80em;
}
Additionally, you could set the style for
input[type="text"] {
width: 200px;
}
- this overrides .text-box and will change all input text boxes, EditorFor or otherwise.
I also had issue with setting the width of TextBox in MVC3, while setting the Clsss attribute worked for TextArea control but not for TextBoxFor control or EditorFor control:
I tried following & that worked for me:
@Html.TextBoxFor(model => model.Title, new { Class = "textBox", style = "width:90%;" })
also in this case Validations are working perfectly.
One way you could get round it is by having delegates on the view model to handle printing out special rendering like this. I've done this for a paging class, I expose a public property on the model Func<int, string> RenderUrl
to deal with it.
So define how the custom bit will be written:
Model.Paging.RenderUrl = (page) => { return string.Concat(@"/foo/", page); };
Output the view for the Paging
class:
@Html.DisplayFor(m => m.Paging)
...and for the actual Paging
view:
@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>
}
It could be seen as over-complicating matters but I use these pagers everywhere and couldn't stand seeing the same boilerplate code to get them rendered.
UPDATE: hm, obviously this won't work because model is passed by value so attributes are not preserved; but I leave this answer as an idea.
Another solution, I think, would be to add your own TextBox/etc helpers, that will check for your own attributes on model.
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)) %>
This one is easier but not as convinient/flexible.
This is the cleanest and most elegant/simple way to get a solution here.
Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.
http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx
I really liked @tjeerdans answer which utilizes the EditorTemplate named String.ascx in the /Views/Shared/EditorTemplates folder. It seems to be the most straight-forward answer to this question. However, I wanted a template using Razor syntax. In addition, it seems that MVC3 uses the String template as a default (see the StackOverflow question "mvc display template for strings is used for integers") so you need to set the model to object rather than string. My template seems to be working so far:
@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})
I solved it!!
For Razor the syntax is:
@Html.TextAreaFor(m=>m.Address, new { style="Width:174px" })
this adjusts the text area width to the width that i defined in the style parameter.
For ASPx the syntax is:
<%=Html.TextAreaFor(m => m.Description, new { cols = "20", rows = "15", style="Width:174px" })%>
this will do the trick
참고URL : https://stackoverflow.com/questions/1625327/editorfor-and-html-properties
'development' 카테고리의 다른 글
C ++ 개인 상속을 언제 사용해야합니까? (0) | 2020.07.27 |
---|---|
RichTextBox (WPF)에는 문자열 속성 "Text"가 없습니다. (0) | 2020.07.27 |
Python으로 ssh를 통해 명령 수행 (0) | 2020.07.27 |
일치하지 않는 익명의 define () 모듈 (0) | 2020.07.26 |
양식 제출 후 Jquery 콜백을 수행하는 방법은 무엇입니까? (0) | 2020.07.26 |