在我的自定义的ValidationSummary扩展自定义HTML(Customizing HTML

2019-11-03 22:02发布

到目前为止,这是工作,但我似乎无法明确在所需的正确顺序的HTML。

对于每一个不同的错误,我需要这个HTML返回:

<div class="style-msg errormsg">
    <div class="sb-msg">
        <i class="icon-remove"></i>
        Error Text
    </div>
</div>

下面是扩展方法:

public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "")
        {
            string retVal = "";
            if (helper.ViewData.ModelState.IsValid)
                return "";
            retVal += "<div class='style-msg errormsg'><div class='sb-msg'><i class='icon-remove'></i>";
            if (!String.IsNullOrEmpty(validationMessage))
                retVal += helper.Encode(validationMessage);
            foreach (var key in helper.ViewData.ModelState.Keys)
            {
                foreach (var err in helper.ViewData.ModelState[key].Errors)
                    retVal += helper.Encode(err.ErrorMessage);
            }
            retVal += "</div></div>";
            return retVal.ToString();
        }
    }

最后在这里是我如何调用它的实际网页。

@Html.Raw(Html.MyValidationSummary())

BONUS问:使用HTML.Raw在这种情况下安全吗?

Answer 1:

玩弄这一点后,我得出了这个结论。 我改变了HTML一点,因为我想用引导警告框。

public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "")
{
    string retVal = "";
    string errorList = "";

    foreach (var key in helper.ViewData.ModelState.Keys)
    {
        retVal = "";

        foreach (var err in helper.ViewData.ModelState[key].Errors)
        {
            retVal += "<div class='alert alert-danger'>";
            retVal += "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>";
            retVal += "<i class='icon-remove-sign'></i>";
            retVal += helper.Encode(err.ErrorMessage);
            retVal += "</div>";
            errorList += retVal;
        }


    }

    return errorList.ToString();
}


文章来源: Customizing HTML in my custom ValidationSummary extension