当满足特定条件时,如何从控制器产生javascript视觉效果?

时间:2012-03-06 13:22:48

标签: javascript jquery asp.net-mvc exception html

我目前正在编写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();
    }
}

,这是此方法的创建视图。

/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位于页面底部。如果控制器中发生异常,我想尝试调用它。忽略实际的错误消息。这甚至可以“远程”吗?或者有更简单的方法吗?

2 个答案:

答案 0 :(得分:1)

您可以考虑在catch语句中返回一个返回JavaScript(script),但不建议这样做。

你真的应该让你的客户做客户方业务。

答案 1 :(得分:0)

我找到了一个针对我的问题的个人解决方法,并且它有效。当满足用户输入的特定条件时,可以调用Javascript。

在您使用的控制器中,声明一个ViewData [“此处名称”]变量,并在其上执行您的条件

    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。