2

我是 MVC 框架的新手,所以请对我温柔一点。我想在不使用 Tag Builder 类的情况下制作强类型的自定义扩展方法。我一直在网上搜索一个
带有解释的例子,但我找不到任何解决方案。请帮我。下面是自定义扩展方法的代码,请告诉我如何将其转换为强类型。

public static MvcHtmlString DateOfBirth(this HtmlHelper helper)
    {
        var text = @"<div>
    <select style=""width: 40px"">";
    for (int i = 1; i <= 31; i++)
    {
        if (i < 10)
        {
            text += "<option>" + 0 + +i + "</option>";
        }
        else
        {
            text += "<option>" + i + "</option>";
        }
    }
text += "</select>";
text += "<select style=\"width: 40px\">";
    for (int i = 1; i <= 12; i++)
    {
        if (i < 10)
        {
            text += "<option>" + 0 + +i + "</option>";
        }
        else
        {
            text += "<option>" + i + "</option>";
        }

    }
 text += "</select>";
 text += "<select style=\"width: 60px\">";
    var date = System.DateTime.Now.Year;
    for (int i = 1950; i <= date; i++)
    {
        text += "<option>"+i+"</option>";
    }
 text += "</select>";
text += "</div>";

        return new MvcHtmlString(text);

    }
4

2 回答 2

1

当这个类正是为此目的而设计时,你为什么不想使用 TagBuilder 呢?你更喜欢写一些标签汤?不。

这里:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class HtmlExtensions
{
    public static IHtmlString DateOfBirthFor<TModel>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, DateTime>> ex
    )
    {
        var days = Enumerable.Range(1, 31).Select(x => new SelectListItem 
        { 
            Value = x.ToString(),
            Text = x.ToString()
        });
        var months = Enumerable.Range(1, 12).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = x.ToString()
        });
        var years = Enumerable.Range(1950, DateTime.Now.Year - 1949).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = x.ToString()
        });

        var result = new TagBuilder("div");
        DateTime dob = (DateTime)ModelMetadata.FromLambdaExpression(ex, html.ViewData).Model;

        result.InnerHtml = string.Concat(
            html.DropDownList("Day", new SelectList(days, "Value", "Text", dob.Day), new { width = "40px" }).ToHtmlString(),
            html.DropDownList("Month", new SelectList(months, "Value", "Text", dob.Month), new { width = "40px" }).ToHtmlString(),
            html.DropDownList("Year", new SelectList(years, "Value", "Text", dob.Year), new { width = "60px" }).ToHtmlString()
        );

        return new HtmlString(result.ToString());
    }
}

接着:

@model MyViewModel
...
@Html.DateOfBirthFor(x => x.Dob)
于 2013-04-01T06:35:21.293 回答
0

使用定义:

public static MvcHtmlString DateOfBirth<TModel> (this HtmlHelper<TModel>)
{ 
   // ...
}

然后它将绑定到特定的 TModel HtmlHelper。

于 2013-04-01T06:29:55.830 回答