4
我想要做的就是能夠在.cshtml文件中寫入與剃刀風格標記和方法混合的javascript,並將其發送給一個單獨的方法供以後使用。如何將包含剃鬚刀標記的內容用作方法的參數?
我的.cshtml看起來是這樣的:
@{SomeClass.SaveForLater(@<script type="text/javascript">window.alert('@Model.SomeParamter')}</script>);
和類SomeClass的內部:
public static void SaveForLater(HtmlString str) {
// will be using str.ToString() here and save the string output for use later on.
}
但我收到這是什麼錯誤消息:
CS1660:不能lambda表達式轉換爲鍵入'System.Web.HtmlString',因爲它不是委託類型
我是使用錯誤類型的參數或d o我需要重新思考整個概念?
解決方案 感謝SLaks下面我落得這樣做:
public static void SaveForLater<T>(Func<T, HelperResult> template, dynamic model)
{
// template(model).ToHtmlString()
}
使用這樣的:
@{SomeClass.SaveForLater<SomeModel>(
@<script type="text/javascript">window.alert('@Model.SomeParamter')</script>,
Model
);
感謝您指引我朝着正確的方向發展,但是如果看一下我的例子,代表什麼是「什麼」類? –
@MattiasHögnäs:任何你想要的。它將被傳遞給行動;看我的博客文章。如果你不想傳遞任何東西,只需使用'object'。 – SLaks