当前位置: 代码迷 >> Ajax >> Jquery与.net MVC组合,通过Ajax
  详细解决方案

Jquery与.net MVC组合,通过Ajax

热度:656   发布时间:2012-08-28 12:37:01.0
Jquery与.net MVC结合,通过Ajax

在工作中做了这么一个东西。

Html端:

@using Test.fh.Project.Storefront.ViewModels
@using Test.fh.Project.Storefront.Services
@model ProductViewModel
<div id="column-left">
    <div class="box">
        <div class="box-heading">
            Categories</div>
        <div class="box-content">
            <div class="box-category">
                
            </div>
        </div>
    </div>
</div>
<div id="content">
    <div class="breadcrumb">
        @Html.Partial("_Breadcrumbs")
    </div>
    <h1>
        @MvcHtmlString.Create(@Model.product_name)
    </h1>
    @using (Html.BeginForm("index", "Product"))
    {
        @Html.ValidationSummary(excludePropertyErrors: true)
        <div class="product-info">
            <div class="left">
                <div class="image">
                    <a href="@Url.Content("~/Content/images/" + @Model.thumbImagePopPath)" title="@Model.product_name"
    class="fancybox" rel="fancybox">
                        <img src="@Url.Content("~/Content/images/" + @Model.thumbImagePath)"  title="@Model.product_name"
    alt="@Model.product_name" id="image" />
                    </a>
                </div>
                @if (Model.imagePaths.Count() > 0)
                {
                    <div class="image-additional">
                        @foreach (var item in Model.imagePaths)
                        {
                            <a href="@Url.Content("~/Content/images/" + @item.imagePopPath)" title="@Model.product_name" class="fancybox" rel="fancybox">
                                <img src="@Url.Content("~/Content/images/" + @item.imagePath)" title="@Model.product_name" alt="@Model.product_name"/>
                            </a>
                        }
                    </div>
                }
            </div>
            <div class="right">
                <div class="description">
                    @if (Model.manufacturer != null || Model.manufacturer != "")
                    {
                        <span>Brand: </span> <a href="@Model.manufacturer_id">@Model.manufacturer</a><br />
                    }
                    <span>Product Code: </span>@Model.model<br />
                    <span>Reward Points:</span> @Model.reward<br />
                    <span>Availability: </span>@Model.stock_status
                </div>
                <div class="price">
                    Price:
                    @if (Model.special == null || Model.special == "")
                    {
                        @Currency.format(Model.price, null, null, true)
                    }
                    else
                    {
                        <span class="price-old">@Currency.format(Model.price, null, null, true)</span>
                        <span class="price-new">@Currency.format(Model.special, null, null, true)</span>
                    }
                    <br />
                    <span class="price-tax">Ex Tax:
                        @if (Model.special != null && Model.special != "")
                        {
                            @Currency.format(Model.special, null, null, true)
                        }
                        else
                        {
                            @Currency.format(Model.price, null, null, true)
                        }
                    </span>
                    <br />
                    <span class="reward"><small>Price in reward points: @Model.points</small></span>
                    <br />
                    <br />
                    <div class="discount">
                        @foreach (var item in ViewBag.Discounts)
                        {
                            @string.Format("({0} or more {1})", @item["quantity"], @Currency.format(item["price"].ToString(), null, null, true));
                            <br />
                        }
                    </div>
                </div>
                @if (ViewBag.Options != null)
                {
                    <div class="options">
                        <h2>
                            Available Options</h2>
                        <br />
                        @foreach (var item in ViewBag.Options)
                        {
                            if (item.Key["type"] == "select")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                <select name="option[@item.Key["product_option_id"]]">
                                    <option value="">--- Please Select ---</option>
                                    @foreach (var option_value in item.Value)
                                    {
                                        <option value="@option_value["product_option_value_id"]">@option_value["name"]
                                            @if (@option_value["price"] != null)
                                            {
                                                @string.Format("({0}{1})", @option_value["price_prefix"], @Currency.format(option_value["price"].ToString(), null, null, true));
                                            }
                                        </option>
                                    }
                                </select>
                            </div>
                            <br />
                            }
                            if (item.Key["type"] == "radio")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                @foreach (var option_value in item.Value)
                                {
                                    <input type="radio" name="option[@option_value["product_option_id"]]" value="@option_value["product_option_value_id"]"
                id="option-value-@option_value["product_option_value_id"]" />
                                    <label for="option-value-@option_value["product_option_value_id"]">@option_value["name"]
                                        @if (@option_value["price"] != null)
                                        {
                                            @string.Format("({0}{1})", @option_value["price_prefix"], @Currency.format(option_value["price"].ToString(), null, null, true));
                                        }
                                    </label>
                                    <br />
                                }
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "checkbox")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                @foreach (var option_value in item.Value)
                                {
                                    <input type="checkbox" name="option[@option_value["product_option_id"]]" value="@option_value["product_option_value_id"]"
                id="option-value-@option_value["product_option_value_id"]" />
                                    <label for="option-value-@option_value["product_option_value_id"]">@option_value["name"]
                                        @if (@option_value["price"] != null)
                                        {
                                            @string.Format("({0}{1})", @option_value["price_prefix"], @Currency.format(option_value["price"].ToString(), null, null, true));
                                        }
                                    </label>
                                    <br />
                                }
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "text")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                <input type="text" name="option[@item.Key["product_option_id"]]"
            value="@item.Key["option_value"]" />
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "textarea")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                <textarea name="option[@item.Key["product_option_id"]]"
            cols="40" rows="5">@item.Key["option_value"]</textarea>
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "file")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                <a id="button-option-option[@item.Key["product_option_id"]]"
            class="button"><span>Upload File</span></a>
                                <input type="hidden" name="option[@item.Key["product_option_id"]]"
            value="" />
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "date")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@item.Key["name"]:</b><br />
                                <input type="text" name="option[@item.Key["product_option_id"]]"
            value="@item.Key["option_value"]" class="date" />
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "datetime")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@MvcHtmlString.Create(@item.Key["name"]):</b><br />
                                <input type="text" name="option[@item.Key["product_option_id"]]"
            value="@item.Key["option_value"]" class="datetime" />
                            </div>
                            <br />
                            }

                            if (item.Key["type"] == "time")
                            {
                            <div id="option-@item.Key["product_option_id"]" class="option">
                                @if (item.Key["required"] != null && item.Key["required"] == 1)
                                {
                                    <span class="required">*</span>
                                }
                                <b>@MvcHtmlString.Create(@item.Key["name"]):</b><br />
                                <input type="text" name="option[@item.Key["product_option_id"]]"
            value="@item.Key["option_value"]" class="time" />
                            </div>
                            <br />
                            }
                        }
                    </div>
                }
                <div class="cart">
                    <div>
                        Qty:
                        @Html.TextBoxFor(model => model.minimum, new { maxlength = 2, name = "quantity" })
                        @Html.HiddenFor(model => model.product_id) &nbsp <a id="button-cart" class="button">
                            <span>Add to Cart</span> </a>
                    </div>
                    <div>
                        <span>&nbsp;&nbsp;&nbsp;- OR -&nbsp;&nbsp;&nbsp;</span>
                    </div>
                    <div>
                        <a onclick="addToWishList('@Model.product_id');">Add to Wish List</a><br />
                        <a onclick="addToCompare('@Model.product_id');">Add to Compare</a>
                    </div>
                    @if (int.Parse(Model.minimum) > 1)
                    {
                        <div class="minimum">
                            This product has a minimum quantity of @Model.minimum</div>
                    }
                </div>
                <div class="review">
                    <div>
                        <img src="@string.Format("/cart/Content/catalog/theme/default/image/stars-{0}.png", Model.rating)" alt="@Model.rating" />&nbsp;&nbsp;
                        <a onclick="$('a[href=\'#tab-review\']').trigger('click');">
                            @Model.reviews reviews </a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick="$('a[href=\'#tab-review\']').trigger('click');">Write
                                a review</a>
                    </div>
                    <div class="share">
                        <!-- AddThis Button BEGIN -->
                        <div class="addthis_default_style">
                            <a class="addthis_button_compact">Share</a> <a class="addthis_button_email"></a>
                            <a class="addthis_button_print"></a><a class="addthis_button_facebook"></a><a class="addthis_button_twitter">
                            </a>
                        </div>
                        <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js"></script>
                        <!-- AddThis Button END -->
                    </div>
                </div>
            </div>
        </div>
        <div id="tabs" class="htabs">
            <a href="#tab-description">Description</a>
            @if (ViewBag.attribute_groups != null)
            {
                <a href="#tab-attribute">Specification</a>
            }
            <a href="#tab-review">Reviews </a>
            @if (ViewBag.relate_products != null)
            {
                <a href="#tab-related">Related Products (@ViewBag.relate_products.Count)</a>
            }
        </div>
        <div id="tab-description" class="tab-content">@Html.Raw(@Model.description)</div>
                                                 if (ViewBag.attribute_groups != null)
                                                 {
        <div id="tab-attribute" class="tab-content">
            <table class="attribute">
                @foreach (var item in ViewBag.attribute_groups)
                {
                    <thead>
                        <tr>
                            <td colspan="2">
                                @item.Key["name"]
                            </td>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var item_att in item.Value)
                        {
                            <tr>
                                <td>@item_att["name"]
                                </td>
                                <td>@item_att["text"]
                                </td>
                            </tr>
                        }
                    </tbody>
                }
            </table>
        </div>
                                                 }
        <div id="tab-review" class="tab-content">
            
        </div>

                                                 if (ViewBag.relate_products != null)
                                                 {
        <div id="tab-related" class="tab-content">
            <div class="box-product">
                @foreach (var item in ViewBag.relate_products)
                {

                    <div>
                        @if (item["image"] != null)
                        {
                            <div class="image">
                                <a href="@item["product_id"]">
                                    <img src="@Url.Content("~/Content/images/" + @item["image"])" alt="@item["name"]"
                /></a></div>
                        }
                        <div class="name">
                            <a href="@item["product_id"]">@item["name"]</a></div>
                        @if (item["price"] != null)
                        {
                            <div class="price">
                                @Currency.format(item["price"].ToString(), null, null, true)
                            </div>
                        }
                        <a onclick="addToCart('@item["product_id"]');" class="button"><span>Add to Cart</span></a></div>
                }
            </div>
        </div>
                                                 }
                                                 if (ViewBag.tags != null)
                                                 {
        <div class="tags">
            <b>Tags:</b>
            @foreach (var item in ViewBag.tags)
            {
                <a href="@item["tag"]">@item["tag"]</a>

            }
        </div>
                                                 }
    }
</div>
@*@Url.Action("Update", "Product");*@
@foreach (var item in ViewBag.Options)
{
    if (item.Key["type"] == "file")
    {
    <script type="text/javascript">
        new AjaxUpload('#button-option-option[@item.Key["product_option_id"]]', {
            action: '/Product/upload',
            name: 'file',
            autoSubmit: true,
            responseType: 'json',
            onSubmit: function (file, extension) {
                $('#button-option-option[@item.Key["product_option_id"]]').after('<img src="catalog/view/theme/default/image/loading.gif" id="loading" style="padding-left: 5px;" />');
            },
            onComplete: function (file, json) {
                $('.error').remove();

                if (json.success) {
                    alert(json.success);

                    $('input[name=option[@item.Key["product_option_id"]]').attr('value', json.file);
                }

                if (json.error) {
                    $('#option-@item.Key["product_option_id"]').after('<span class="error">' + json.error + '</span>');
                }

                $('#loading').remove();
            }
        });
    </script>
    }
}
<script type="text/javascript">
    $('.fancybox').fancybox({ cyclic: true });
</script>
<script type="text/javascript">
    $('#tabs a').tabs();
</script>
<script type="text/javascript" src="@Url.Content("~/Content/Admin/js/jquery/ui/jquery-ui-timepicker-addon.js")"></script>
<script type="text/javascript"><!--
    if ($.browser.msie && $.browser.version == 6) {
        $('.date, .datetime, .time').bgIframe();
    }
    $('.date').datepicker({ dateFormat: 'yy-mm-dd' });
    $('.datetime').datetimepicker({
        dateFormat: 'yy-mm-dd',
        timeFormat: 'h:m'
    });
    $('.time').timepicker({ timeFormat: 'h:m' });
    //这行是重点
    $('#button-cart').bind('click', function () {
        //alert($('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'));
        $.ajax({
            url: '@Url.Action("Update", "Cart", new { area = "" })',
            type: 'post',
            data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
            dataType: 'json',
            success: function (json) {
                $('.success, .warning, .attention, information, .error').remove();

                if (json['warning']) {

                    $('#notification').html('<div class="warning" style="display: none;">' + json['warning'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

                    $('.warning').fadeIn('slow');

                }
                if (json['option_error']) {
                    for (i in json['option_error']) {
                        //alert(i);
                        $('#option-' + i).after('<span class="error">' + json['option_error'][i] + '</span>');
                    }
                }
                if (json['success']) {
                    //$('#notification').html('<div class="attention" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');

                    //$('.attention').fadeIn('slow');

                    //$('#cart_total').html(json['total']);

                    //$('html, body').animate({ scrollTop: 0 }, 'slow');

                }
            }
        });
    });
//-->
</script>

?后台端

[HttpPost]
        public JsonResult Update()
        {
            Dictionary<string, object> jsonMesg_dict = new Dictionary<string, object>();

            ProductService pservice = new ProductService();
            SessionEntityService sessionService = new SessionEntityService();
            //Request.Params["××××"];是重点
            string product_id = Request.Params["product_id"];
            Dictionary<string, string> options = this.arrayFilterOption(Request.Params);
            string key = product_id + ":" + new OpenSharp.Storefront.Models.Tool.PHPSerializer().Serialize(options);
            Entity product = null;

            if (product_id != null)
            {
                int customer_group_id = 8;
                product = pservice.getProduct(int.Parse(product_id), customer_group_id, languagedId);
            }

            if (product != null)
            {
                int product_total = 0;
                int quantity = 1;
                if (Request.Params["minimum"] != null)
                {
                    quantity = int.Parse(Request.Params["minimum"]);

                    SessionEntity session = sessionService.GetSessionEntity();

                    ShopCart cartItem = session.ShopCart;

                    foreach (KeyValuePair<string, ShopProduct> sp in cartItem.Items)
                    {
                        if (sp.Key.Equals(key))
                        {
                            product_total = sp.Value.Quantity;
                        }
                    }

                    string str_error_json = string.Empty;
                    if (int.Parse(product["minimum"].ToString()) > (product_total + quantity))
                    {
                        str_error_json = string.Format("Minimum order amount for {0} is {1}!", product["name"], product["minimum"]);
                        jsonMesg_dict.Add("warning", str_error_json);
                    }

                    Dictionary<Entity, Entities> poptions = pservice.getProductOptions(int.Parse(product_id), languagedId);

                    Dictionary<string, string> dic_error_json = new Dictionary<string, string>();
                    jsonMesg_dict.Add("option_error", dic_error_json);
                    foreach (var item in poptions)
                    {
                        int optionID = int.Parse(item.Key["product_option_id"].ToString());
                        if (int.Parse(item.Key["required"].ToString()) == 1)
                        {
                            string str = "option[" + optionID + "]";
                            if (!options.ContainsKey(str) || (options[str] == null || options[str].Equals("")))
                            {
                                string error_json = string.Format("{0} required!", item.Key["name"]);
                                dic_error_json.Add(optionID.ToString(), error_json);
                            }
                        }
                    }

                    if (jsonMesg_dict.Count == 0)
                    {
                        ShopProduct tempShoppingP = new ShopProduct();
                        tempShoppingP.ProductId = int.Parse(product_id);
                        tempShoppingP.Options = new OpenSharp.Storefront.Models.Tool.PHPSerializer().Serialize(options);
                        tempShoppingP.Quantity = quantity;

                        //Please pay attention on the following line.
                        //                        if (product["special"] == null || product["special"] == "")
                        if (string.IsNullOrEmpty(product["special"].ToString()))
                        {
                            tempShoppingP.UnitPrice = double.Parse(product["price"].ToString());
                        }
                        else
                        {
                            tempShoppingP.UnitPrice = double.Parse(product["special"].ToString());
                        }
                        tempShoppingP.ItemCalculate();

                        cartItem.Calculate(tempShoppingP);

                        jsonMesg_dict.Add("success", product["name"].ToString());
                    }
                    else
                    {
                    }
                }
            }
            return Json(jsonMesg_dict, JsonRequestBehavior.AllowGet);
        }
  相关解决方案