gpt4 book ai didi

c# - ASP.NET MVC Helpers,为模型的两个属性创建助手

转载 作者:行者123 更新时间:2023-11-30 20:45:55 24 4
gpt4 key购买 nike

我需要为模型的两个属性创建助手例如

@Html.TestFor(m => m.Item1, m=>m.Item2)

那么如何为这个助手编写方法呢?

例如

public static MvcHtmlString TestFor<TModel, TValue>
(this HtmlHelper<TModel> self,
Expression<Func<TModel, TValue>> expression)
{
...
}

它是仅针对模型的一个属性的方法。怎么能写几个属性呢?感谢您的想法

最佳答案

如果属性类型彼此不同,请像这样使用:

public static MvcHtmlString ImageFor<TModel, TProperty, KProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expressionImageProperty,//this is HttpPostedFile
Expression<Func<TModel, KProperty>> expressionImageIdProperty,//this property is ID for image that store in database
object filehtmlAttributes, object imageBoxHtmlAttributes)//html attributes for html controls
{
var sb = new StringBuilder();
var fileattr = new RouteValueDictionary(filehtmlAttributes);
if (!fileattr.ContainsKey("id"))
fileattr.Add("id", string.Format("ImageForFile_{0}", ((MemberExpression)expressionImageProperty.Body).Member.Name));
fileattr.Add("type", "file");
if (!fileattr.ContainsKey("class"))
fileattr.Add("class", "form-control");
fileattr.Add("onchange", "readURL(this);");
sb.Append((string)htmlHelper.TextBoxFor<TModel, TProperty>(expressionImageProperty, fileattr).ToHtmlString());

TagBuilder tagImg = new TagBuilder("img");
tagImg.Attributes.Add("id", string.Format("ImageForFileViewer_{0}", ((MemberExpression)expressionImageProperty.Body).Member.Name));

if (htmlHelper.ViewData.Model == null)
tagImg.Attributes.Add("src",
new UrlHelper(HttpContext.Current.Request.RequestContext).Action("GetImage", "ImageManagement",
new { imageId = "0" }));
else
{
var modelImageId = expressionImageIdProperty.Compile()(htmlHelper.ViewData.Model).ToString();
if (string.IsNullOrEmpty(modelImageId))
modelImageId = "0";
tagImg.Attributes.Add("src",
new UrlHelper(HttpContext.Current.Request.RequestContext).Action("GetImage", "ImageManagement", //ImageManagementController get FileResult
new
{
imageId = modelImageId,thumb=true,size="small"
}));
}

if (imageBoxHtmlAttributes != null)//
tagImg.MergeAttributes(new RouteValueDictionary(imageBoxHtmlAttributes));//

sb.Append(tagImg.ToString(TagRenderMode.Normal));

sb.Append((string)htmlHelper.HiddenFor<TModel, KProperty>(expressionImageIdProperty).ToHtmlString()); //for update

sb.AppendLine(
EngineContext.Current.Resolve<IPageScriptManager>()//this is simple mvc script manager resolved from IOC
.ScriptInclude<CommonResourceAccessor>("imageFor" + "_script",
"***.WebFramework.Resources.ImageFor.js")//if you have some js file add as resource
.Render().ToString());
return MvcHtmlString.Create(sb.ToString());
}

关于c# - ASP.NET MVC Helpers,为模型的两个属性创建助手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27578862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com