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)   <a id="button-cart" class="button">
- <span>Add to Cart</span> </a>
- </div>
- <div>
- <span> - OR - </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" />
- <a onclick="$('a[href=\'#tab-review\']').trigger('click');">
- @Model.reviews reviews </a> | <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);
- }
Jquery与.net MVC结合,通过Ajax的更多相关文章
- MVC4 AspNet MVC下的Ajax / 使用微软提供的Ajax请求脚本 [jquery.unobtrusive-ajax.min.js]
源码参考:链接:http://pan.baidu.com/s/1pKhHHMj 密码:mkr4 1:新建-->项目-->Web-->ASP.NET MVC 4 Web 应用程序.命 ...
- ASP.NET MVC学习之Ajax(完结)
一.前言 通过上面的一番学习,大家一定收获不少.但是总归会有一个结束的时候,但是这个结束也意味着新的开始. 如果你是从事ASP.NET开发,并且也使用了第三方控件,那么一定会觉得ASP.NET开发aj ...
- MVC中的Ajax(AjaxHelper)
authour: chenboyi updatetime: 2015-04-30 20:47:49 friendly link: 目录 1,思维导图 2,ActionLink() 3,BeginF ...
- bootstrap-data-target触发模态弹出窗元素的data使用 data-toggle与data-target的作用 深入ASP.NET MVC之九:Ajax支持 Asp.Net MVC4系列--进阶篇之AJAX
bootstrap-data-target触发模态弹出窗元素的data使用 时间:2017-05-27 14:22:34 阅读:4479 评论:0 收藏:0 [ ...
- [转]深入ASP.NET MVC之九:Ajax支持
本文转自:http://www.cnblogs.com/yinzixin/archive/2012/12/22/2824384.html 目前前端页面和服务端进行Ajax交互大多采用的都是jQuery ...
- jQuery源码分析系列(31) : Ajax deferred实现
AJAX的底层实现都是浏览器提供的,所以任何基于api上面的框架或者库,都只是说对于功能的灵活与兼容维护性做出最优的扩展 ajax请求的流程: 1.通过 new XMLHttpRequest 或其它的 ...
- 利用jQuery与.ashx完成简单的Ajax
在ASP.NET同样可以与其它编程语言一样,利用前台的Ajax技术,只是需要注意的是,后台的处理程序不再是一个aspx页面中的Page_Load,而且ASP.NET独有的“一般处理程序”.ashx,下 ...
- jquery序列化from表单使用ajax提交返回json数据(使用struts2注解result type = json)
1.action类引入struts2的"json-default"拦截器栈 @ParentPackage("json-default") //示例 @Paren ...
- 类似jQuery的原生JS封装的ajax方法
一,前言: 前文,我们介绍了ajax的原理和核心内容,主要讲的是ajax从前端到后端的数据传递的整个过程. Ajax工作原理和原生JS的ajax封装 真正的核心就是这段代码: var xhr = ne ...
- Jquery 一次处理多个ajax请求的代码
Jquery 一次处理多个ajax请求的代码,需要的朋友可以参考下. 复制代码代码如下: $(document).ready(function () { $('#getsetgo').click( ...
随机推荐
- java的IO总结(一)
Java的IO流是实现输入输出的基础,这里所说的流就是数据流,大部分的与流相关的类放在Java.io包下. 一,Java的流分类 按照不同的分类方式可以把流分成不同的类型,下面我们从不同的角度对流进行 ...
- 在为shader program pass uniform之前一定要先use program。
在为shader program pass uniform之前一定要先use program.
- 4X4矩阵键盘扫描程序
4X4矩阵键盘扫描: 1. 4根行线的GIO均设为Output,根列线的GIO均设为Input: 2. 4根行线的GIO分别置为0111.1011.1101.1110,读逐一读取列线GIO的值,可确定 ...
- php分页函数示例代码
分享一例php分页函数代码,用此函数实现分页代码很不错. 代码,php分页函数. <?php /* * Created on 2011-07-28 * Author : LKK , http:/ ...
- [na]wireshark添加显示ip.id列
wireshark添加ip.id字段 为了在多个设备上追踪同一个数据包. 如果是同一个会话,则可以计算延迟, 如sta和应用服务器慢,这种问题,可以根据这个加上ip.id追踪数据到哪里慢了.
- 深入理解node.js的module.export 和 export方法的区别
你肯定非常熟悉nodejs模块中的exports对象,你可以用它创建你的模块.例如:(假设这是rocker.js文件) exports.name = function() { console.log( ...
- mac下framework联编需要设置的
点击target,然后,在Build Phases里的空白处用鼠标点一下(艹 变态) 这时,点最上面菜单:Editor/Add Build Phases/Add Copy Files Build Ph ...
- 解决python2.7 UnicodeDecodeError和UnicodeEncodeError问题
最近在项目中,读取上传的csv文件,并写入时,会报编码问题, with open(origin_file_path, mode='wb')as f: for chunk in file_obj: f. ...
- TCP/IP协议分析
一;前言 学习过TCP/IP协议的人多有一种感觉,这东西太抽象了,没有什么数据实例,看完不久就忘了.本文将介绍一种直观的学习方法,利用协议分析工具学习TCP/IP,在学习的过程中能直观的看到数据的具体 ...
- VC++ 知识点
1.寻找文件时,CFileFind类的使用. 2.寻找目录时使用BROWSEINFO,其中包含了用户选中目录的重要信息. 3.LPITEMIDLIST类 4.目录选择对话框的使用SHBrowseFor ...