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( ...
随机推荐
- 2.Java基础:方法定义和调用
一.方法的定义 1.类的方法代表的是实力的某种行为(或功能) 方法的定义:方法类型 . 方法签名 . 方法体 2.定义类的方法 访问修饰符 类型 方法名(参数列表){ ///方法体 } 3.把方法当作 ...
- 转inux Shell编程入门
http://www.cnblogs.com/suyang/archive/2008/05/18/1201990.html 从程序员的角度来看, Shell本身是一种用C语言编写的程序,从用户的角度来 ...
- mysql格式化日期
mysql查询记录如果有时间戳字段时,查看结果不方便,不能即时看到时间戳代表的含义,现提供mysql格式换时间函数,可以方便的看到格式化后的时间. 1. DATE_FORMAT() 函数用于以不同的格 ...
- GPS轨迹数据集免费下载资源整理
https://blog.csdn.net/liangyihuai/article/details/58335510
- 使用Frame控件设计Silverlight的导航
这里所说的导航其实就是在Silverlight的页面之间前进后退以及跳转.通过Frame控件配合后台NavigationService类可以很容易的做到页面之间的导航. 这就是工具箱中的Frame控件 ...
- Android:EditText 属性
Android开发EditText属性 EditText 官网链接 EditText继承关系:View-->TextView-->EditText EditText 部分属性: XML 设 ...
- [javase学习笔记]-6.3 对象的内存体现
这一节我们来简单的看一看对象在内存中是什么样子呢,怎样体现. 我们以上一节的測试代码为例. 我们在函数的内存分配分析过.当该代码执行时,首先会载入主函数在栈内存中为main函数分配一个空间: 然后执行 ...
- 图解TCP/IP笔记-网络基础知识
1.计算机网络发展的7个阶段1)批处理服务器一次只能处理一批程序指令2)分时服务器可以分时为多台客户端服务3)计算机之间通信计算机之间由通信线路连接,互相通信4)计算机网络的产生通过分组交换技术,在不 ...
- Oracle中文字符乱码?设置Oracle客户端字符编码与服务端一致
经常可能出现查询Oracle数据时,中文显示乱码,这很可能是因为,Oracle服务端的字符编码与客户端不一致引起的. 这时,我们需要做的是,如何设置自己的客户端字符编码与服务端一致. 查询Oracle ...
- MFC图形编辑器
前言 vs2015竟然可以完美打开工程,哈哈可以直接生成类图了.由于内容较多,所以根据内容的重要性会安排详略. https://github.com/bajdcc/GraphEditor/releas ...