我找到了解決辦法早就忘了回到這裏後......我不能發表一切,我做到了,但其基本思想是將屬性添加到ISettings
接口,如:
public interface ISettings
{
string Name { get; }
string EditorTemplatePath { get; }
}
然後你需要在每個類中重寫這個。例如:
public class SettingsA : ISettings
{
public string Name { get { return "Example A"; } }
public string EditorTemplatePath
{
get{ return "~/Views/Shared/EditorTemplates/SettingsA.cshtml"; }
}
public string CustomAttributeA1 { get; set; }
public string CustomAttributeA2 { get; set; }
}
public class SettingsB : ISettings
{
public string Name { get { return "Example B"; } }
public string EditorTemplatePath
{
get{ return "~/Views/Shared/EditorTemplates/SettingsB.cshtml"; }
}
public string CustomAttributeB1 { get; set; }
public string CustomAttributeB2 { get; set; }
}
當然,您需要在控制器的某處實現自己的邏輯來返回自定義HTML。對於我來說,我使用AJAX和做這樣的事情:
[Route("get-editor-ui/{type}")]
public ActionResult GetEditorUI(string type)
{
var model = // logic to get the model from "type" argument
if (model == null)
{
return HttpNotFound();
}
string content = RenderRazorPartialViewToString(model.EditorTemplatePath, model);
return Json(new { Content = content }, JsonRequestBehavior.AllowGet);
}
僅供參考,RenderRazorPartialViewToString
是我的基本控制器和定義如下:
public string RenderRazorPartialViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
一個解決方案一個粗略的想法將是寫一個基於反射的,CSS類生成器。 –
查看MVC中的HTML自定義編輯器。你可以寫出自己的html擴展名並獲得你想要的結果。例如:@ Html.MattEditorForModel(Model)。這是非常簡單和乾淨的方式。 http://www.c-sharpcorner.com/UploadFile/ashish_2008/htmlhelper-methods-in-Asp-Net-mvc1/ –