我目前正在編寫一個ASP.MVC應用程序。我幾乎完成了它。我現在正在做網站的外觀和感覺。問題是我在我的視圖中有一段javascript,我想從控制器調用滿足特定條件的javascript。滿足特定條件時,如何從控制器產生JavaScript視覺效果?
這裏是代碼示例。
MenuController.cs:
[HttpPost]
public ActionResult Create(FormCollection collection,Models.Menu sentData)
{
try
{
// TODO: Add insert logic here
//db.Menus.AddObject(sentData);
int existingQuery = (from m in db.Menus where m.Weekstart == Helper.GetNextMonday() && m.category == sentData.category select m).Count();
if (existingQuery > 0)
{
throw new Exception();
}
Models.Menu MenuItem = new Models.Menu
{
Monday = sentData.Monday,
Wednesday = sentData.Wednesday,
Friday = sentData.Friday,
category = sentData.category,
Weekstart = Helper.GetNextMonday(),
};
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
//Javascript visual here
return View();
}
}
,這裏是該方法的創建視圖。
/Menu/Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Lunch_Ordering_Application.Models.Menu>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Create</h2>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<div class="editor-label">
<%: Html.LabelFor(model => model.Monday) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Monday) %>
<%: Html.ValidationMessageFor(model => model.Monday) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Wednesday) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Wednesday) %>
<%: Html.ValidationMessageFor(model => model.Wednesday) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Friday) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Friday) %>
<%: Html.ValidationMessageFor(model => model.Friday) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.category) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.category,new SelectList(new List<string> {"Nothing","Traditional","Chill Out","Healthy Lifestyle","Vegitarian","Salad"})) %>
<%: Html.ValidationMessageFor(model => model.category) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
<script src="/js/all.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
ReadyMade.init();
$('.growl_trigger').live('click', function (e) {e.preventDefault();
$.msgGrowl({type: error, title: "Error!", text: 'The category for this list is already listed for next week Monday! Please change the categories here.'});
});
</script>
<div class="msgGrowl-container bottom-right"></div>
</asp:Content>
的JavaScript是在頁面的底部。如果控制器中發生異常,我想嘗試調用它。忽略實際的錯誤信息。這甚至可以「遠程」嗎?還是有更簡單的方法?
1小時,我發現沒有好的解決方案。不過謝謝。標記答案。 – Eon 2012-03-06 14:29:51