今天,遍歷一個HashSet集合對象,想用鏈接綁定集合對象的值,通過POST方式提交到控制器。結果程序無反應,按F12鍵進入調試模式,谷歌總是提示Uncaught ReferenceError: is not defined這個錯誤。
原來是雖然是傳遞的值,但是在函數傳參的時候也要加引號,加上引號后就不會提示 Uncaught ReferenceError: is not define 了。
View :
@using MajorConstruction.Helpers;
@{
ViewBag.Title = "更改主題";
}
<h2>@ViewBag.Title</h2>
<hr />
<div class="container">
<div class="row">
@foreach (var theme in Bootstrap.Themes)
{
<div class="col-md-3">
<div class="panel panel-default">
<div class="panel-body">
<h2>@theme</h2>
<br />
<br />
<p>
@{
bool IsCurrent = theme == HttpContext.Current.Application["CssTheme"].ToString(); //Application 應用程序全局對象。
string btnDisabled = IsCurrent ? "disabled" : null;
}
<a class="btn btn-success @btnDisabled" href="javascript:SetActive('@theme')">應用主題</a> <!--把主題綁定在JavaScript函數上,通過調用Javascript函數提交隱藏表彰。-->
<!--還需要特別注意,調用 javascript 函數的參數@theme必須加引號,如果不加引號,總是谷哥瀏覽器總是提示 Uncaught ReferenceError: XX 未定義 is not defined,因為@theme變量本來就不是值類型,而是HashSet類型-->
</p>
</div>
</div>
</div>
}
</div>
</div>
@using (Html.BeginForm("ChangeTheme", "Theme", FormMethod.Post, new { id = "themeForm" }))
{
@Html.AntiForgeryToken()
<input type="hidden" name="theme" id="themeInput" />
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
var changeThemeUrl = '@Url.Action("ChangeTheme")';
function SetActive(themename) {
$("#themeInput").val(themename); //將參數值傳遞給隱藏表單。
$("#themeForm").submit(); //提交表單,將 theme=themename 發送至控制器POST 方法中。
}
</script>
}
控制器:
public class ThemeController : Controller
{
// GET: Admin/Theme
public ActionResult ChangeTheme()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeTheme(string theme)
{
HttpContext.Application["CssTheme"] = theme;
return View();
}
Bootstrap 類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MajorConstruction.Helpers
{
public class Bootstrap
{
public const string BundleBase = "~/Content/css";
//類作為一個類的成員。
public class Theme
{
public const string Cerulean = "Cerulean";
public const string Darkly = "Darkly";
public const string Flatly = "Flatly";
public const string Spacelab = "Spacelab";
public const string Stock = "Stock";
public const string Superhero = "Superhero";
}
public static HashSet<string> Themes = new HashSet<string>
{
Theme.Cerulean,
Theme.Darkly,
Theme.Flatly,
Theme.Spacelab,
Theme.Stock,
Theme.Superhero
};
public static string Bundle(string themename)
{
return BundleBase + themename;
}
}
}
