实际上,您不能在部分视图中调用脚本部分,并在其中执行此方法。这是设计。见达林的post here
你可以做的是,保持这种方法在主视图。如果需要,您仍然可以从部分视图有条件地执行此操作。
所以在您的主视图
<script>
var mySettings = mySettings || {};
mySettings.shouldIShowSpectrum = false;
</script>
@Html.Partial("YourPartialViewNameHere")
@section scripts
{
<script>
function enableSpectrum() {
$(".basic").spectrum({
color: "#f00",
change: function (color) {
$("#basic-log").text("change called: " + color.toHexString());
}
});
}
// You can put the above method in an external js file as well.
$(function() {
if (mySettings.shouldIShowSpectrum)
{
enableSpectrum();
}
});
</script>
}
,并在您的局部视图,您可以设置mySettings.shouldIShowSpectrum
值true,这样当页面获取呈现它将使你的插件。
<h5>My Partial</h5>
<input type='text' class="basic" />
<em id='basic-log'></em>
<script>
console.log("going to enable the plugin");
var mySettings = mySettings || {};
mySettings.shouldIShowSpectrum = true;
</script>
请问您可以添加什么代码是“不能正常工作”? – pyroglass
刚刚更新了问题 – SAS20
这可能会启发你http://stackoverflow.com/questions/7556400/injecting-content-into-specific-sections-from-a-partial-view-asp-net-mvc-3-with。简而言之:在您的主视图中包含该脚本。 – Shyju