Using System.Reflection to Get a Method's Full Name

后端 未结 8 1372
执念已碎
执念已碎 2020-12-13 06:00

I have a class that look like the following:

public class MyClass
{

...

    protected void MyMethod()
    {
    ...
    string myName = System.Reflection.M         


        
8条回答
  •  有刺的猬
    2020-12-13 06:47

    Thanks for the posts above, they helped me to create a strong type binding system for MVC 4 HTMLHelpers as follows.

     public static MvcHtmlString StrongTypeBinder(this HtmlHelper htmlhelper, Expression> SomeLambda)
        {
            var body = SomeLambda.Body;
            var propertyName = ((PropertyInfo)((MemberExpression)body).Member).Name;
            HtmlString = @"
                
                ";
            HtmlString = HtmlString.Replace("@Id", propertyName);
            var finalstring = new MvcHtmlString(HtmlString);
            return finalstring;
    
        }
    

    To use the code above in any CSHTML View:

    @Html.StrongTypeBinder(p=>Model.SelectedDate)
    

    This allows me to bind any property in a ViewModel to any HTML element type I want. In the example above, I an binding the name field for the selected data posted back after user makes selection. The viewmodel after the post back automatically shows the selected value.

提交回复
热议问题