简体   繁体   中英

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

I am currently writing a ASP.MVC application. I am almost done with it. I am now doing the look and feel of the website. The problem is that I have piece of javascript in my view which I would like to call from my controller when a specific condition is met.

Here is the code examples.

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();
    }
}

and here is the create view for this method.

/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>

The javascript is at the bottom of the page. I want to attempt to call it if an exception occurs in the controller. Ignore the actual error message. Is this even "remotely" possible? Or is there an easier way?

You can consider return a return JavaScript(script) in your catch statement, however, it's not recommended.

you really should let your client do client side business.

I have found a personal workaround for my issue, and it works. Javascript can be called when a specific condition from user-input is met.

In the controller that you use, declare a ViewData["name here"] Variable, and perform your condition on it

    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();
        }
    }

And in the 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, its a perfectly valid workaround for when a specific condition is met, that a piece of javascript/jquery can be run from this point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM