-
Notifications
You must be signed in to change notification settings - Fork 0
/
HtmlHelperExtensions.cs
70 lines (56 loc) · 2.2 KB
/
HtmlHelperExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace WebApp.MVC.Core.Extensions
{
public static class HtmlHelperExtensions
{
/// <summary>
/// ネストされたPartialViewを考慮したモデルバインディングに対応する描画処理
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="partialViewName"></param>
/// <param name="expression"></param>
public static void RenderPartialFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
string partialViewName,
Expression<Func<TModel, TProperty>> expression)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var model = metadata.Model;
var oldTemplateInfo = htmlHelper.ViewData.TemplateInfo;
var newPrefix = ExpressionHelper.GetExpressionText(expression);
if (oldTemplateInfo.HtmlFieldPrefix.Length > 0)
{
// 呼び出し元のExpression考慮
if (newPrefix.StartsWith("[") && newPrefix.EndsWith("]"))
{
// 配列バインディング考慮
// old: UserList new: [0] → UserList[0]
newPrefix = oldTemplateInfo.HtmlFieldPrefix + newPrefix;
}
else
{
// old: User new: Name → User.Name
newPrefix = oldTemplateInfo.HtmlFieldPrefix + (string.IsNullOrEmpty(newPrefix) ? "" : "." + newPrefix);
}
}
var templateInfo = new TemplateInfo
{
HtmlFieldPrefix = newPrefix,
};
var viewData = new ViewDataDictionary(htmlHelper.ViewData)
{
TemplateInfo = templateInfo,
};
htmlHelper.RenderPartial(partialViewName, model, viewData);
}
}
}