How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

前端 未结 14 1865
一向
一向 2021-02-06 21:20

How can i Set RadioButtonFor() as Checked By Default

<%=Html.RadioButtonFor(m => m.Gender,\"Male\")%>

there is way out for (Html.Radio

14条回答
  •  难免孤独
    2021-02-06 21:55

    This Helper evaluates the expression and if equals to the value it checks the radio button, and has the same parameters than RadioButtonFor (for this reason the name is diferent):

    public static MvcHtmlString CheckedRadioButtonFor(this HtmlHelper htmlHelper, Expression> expression, object value)
    {
        return CheckedRadioButtonFor(htmlHelper, expression, value, null);
    }
    
    public static MvcHtmlString CheckedRadioButtonFor(this HtmlHelper htmlHelper, Expression> expression, object value, object htmlAttributes)
    {
        var func = expression.Compile();
        var attributes = new RouteValueDictionary(htmlAttributes);
        if ((object)func(htmlHelper.ViewData.Model) == value) {
            attributes["checked"] = "checked";
        }
        return htmlHelper.RadioButtonFor(expression, value, attributes);
    }
    

    Usage:

    <%= Html.CheckedRadioButtonFor(m => m.Gender, "Male", new { id = "gender-male" })%>
    

    Result:

    
    
    
    
    

提交回复
热议问题