簡體   English   中英

滿足特定條件時,如何從控制器引起javascript視覺效果?

[英]How do I cause a javascript visual effect from a controller when specific conditions are met?

我目前正在編寫一個ASP.MVC應用程序。 我幾乎完成了。 我現在正在做網站的外觀。 問題是我的視圖中有一段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();
    }
}

這是此方法的創建視圖。

/菜單/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位於頁面底部。 如果控制器中發生異常,我想嘗試調用它。 忽略實際的錯誤信息。 這甚至“遙遙”可行嗎? 還是有更簡單的方法?

您可以考慮在catch語句中返回return JavaScript(script) ,但是不建議這樣做。

您確實應該讓您的客戶進行客戶端業務。

我發現了針對我的問題的個人解決方法,它可以工作。 當滿足用戶輸入的特定條件時,可以調用Javascript。

在您使用的控制器中,聲明一個ViewData [“ name here”]變量,並在其上執行條件

    public ActionResult Create()
    {
        ViewData["error"] = false;
        ViewData["Heading"] = "Create a new menu Item";
        return View();
    }

    [HttpPost]
    public ActionResult Create(FormCollection collection,Models.Menu sentData)
    {
        try
        {
            // TODO: Add insert logic here
            //db.Menus.AddObject(sentData);
            ViewData["Heading"] = "Create a new menu Item";
            DateTime MondaysDate = Helper.GetNextMonday();
            bool existingQuery = ((from m in db.Menus where m.Weekstart == MondaysDate.Date && m.category == sentData.category select m).Count() > 1) ? true : false;

            if (existingQuery)
            {
                ViewData["error"] = true;
                return View();
            }
            else
            {
                Models.Menu MenuItem = new Models.Menu
                {
                    Monday = sentData.Monday,
                    Wednesday = sentData.Wednesday,
                    Friday = sentData.Friday,
                    category = sentData.category,
                    Weekstart = Helper.GetNextMonday(),
                };
                db.Menus.AddObject(MenuItem);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        catch
        {
                            //ViewData["error"] can also be set here
            return View();
        }
    }

並在視圖中:

  <script src="/js/all.js" type="text/javascript"></script>
    <% if ((bool)ViewData["error"] == true)
       { %>
    <script type="text/javascript">        $(function () {
            ReadyMade.init();
            $.msgGrowl({ type: 'error', title: 'Failed to insert record', text: 'Regretfully, your record can not be entered into the database, as menu items of this category is already booked for next Monday. Kindly change the category to something else.'
            });
        });</script>
    <%} %>

IMO,對於滿足特定條件的情況,這是一個非常有效的解決方法,此刻可以運行一段javascript / jquery。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM