我在MVC 5项目中有一个自定义控件。最后,我想添加一个“保存”按钮和一个ValidationSummary(在WriteSubmitControls方法中)。验证摘要是使用HtmlHelper的实例构建的。似乎HtmlHelper
和AjaxHelper
应该共享一个基类或接口,但看起来却没有。
如何在不传递HtmlHelper实例的情况下访问它?
public class MyCustomAjaxForm: IDisposable
{
private readonly MvcForm _ajaxForm;
public MyCustomAjaxForm(AjaxHelper ajaxHelper)
{
_ajaxForm = ajaxHelper.BeginForm("Save", "Contacts", routeValues, ajaxOptions);
}
private void WriteSubmitControls()
{
_writer.WriteLine("<button type='submit'>Save</button>");
// Output Validation Summary Here
}
public void Dispose()
{
WriteSubmitControls();
_ajaxForm.Dispose();
}
}
答案 0 :(得分:1)
我想我找到了一个解决方案,但是不确定这是否是最好的方法。我使用HtmlHelper
中的ViewContext
和ViewDataContainer
创建了AjaxHelper
的新实例。
public class MyCustomAjaxForm: IDisposable
{
private readonly MvcForm _ajaxForm;
private readonly HtmlHelper _htmlHelper;
public MyCustomAjaxForm(AjaxHelper ajaxHelper)
{
_ajaxForm = ajaxHelper.BeginForm("Save", "Contacts", routeValues, ajaxOptions);
//create instance of HtmlHelper
_htmlHelper = new HtmlHelper(ajaxHelper.ViewContext, ajaxHelper.ViewDataContainer);
}
private void WriteSubmitControls()
{
_writer.WriteLine("<button type='submit'>Save</button>");
//output ValidationSummary using instance of HtmlHelper
_writer.WriteLine(_htmlHelper.ValidationSummary(true));
}
public void Dispose()
{
WriteSubmitControls();
_ajaxForm.Dispose();
}
}