初识MVC web框架--Controller与View交互1
作者:互联网
在基于Web框架开发的软件中,Controller和View之间传递数据是常有的,下面我们来领略下Controller与View各种数据交互方式的风采。
方式一:ViewBag\ViewData\TempData
ViewBag 是动态类型(dynamic),ViewData 是一个字典型的(Dictionary),TempData的使用同ViewData和ViewBag一样,TempData也可以用来向视图传递数据。只是ViewData和ViewBag的生命周期和View相同,只对当前View有用。而TempData则可以在不同的Action中进行传值。
1. ViewData与TempData方式是弱类型的方式传递数据,而使用Model传递数据是强类型的方式。
2. ViewData与TempData是完全不同的数据类型,ViewData数据类型是ViewDataDictionary类的实例化对象,而TempData的数据类型是TempDataDictionary类的实例化对象。
3. TempData实际上保存在Session中,控制器每次执行请求时都会从Session中获取TempData数据并删除该Session。TempData数据只能在控制器中传递一次,其中的每个元素也只能被访问一次,访问之后会被自动删除。
4. ViewData只能在一个Action方法中进行设置,在相关的视图页面读取,只对当前视图有效。理论上,TempData应该可以在一个Action中设置,多个页面读取。但是,实际上TempData中的元素被访问一次以后就会被删除。
5. 在MVC3开始,视图数据可以通过ViewBag属性访问,在MVC2中则是使用ViewData。MVC3中保留了ViewData的使用,有关他们之间的区别可以参考这个文章。
Controller里面赋值: public ActionResult Index() { ViewBag.hello = "hello,this is viewBag"; ViewData["hi"] = "hi,this is viewData"; TempData["abc"] = "this is tempdata"; return View(); } View里面调用: <h2>关于</h2> <p> @ViewBag.hello @ViewData["key"] @TempData["abc"] </p>
View层表单代码:
@model SaleOrderViewModel @using (Html.BeginForm("SalesOrderEdit", "Order", FormMethod.Post, new { id = "SalesOrderEditForm", enctype = "multipart/form-data" })) { @Html.HiddenFor(m => m.SaleOrderID) <div class="form-horizontal"> <div class="page-header"> <h3>@this.Intl("Common.BasicInfo")</h3> </div> <div class="form-group"> @Html.ResourceLabelFor(model => model.SaleOrderNo, new { @class = "control-label col-md-2 field-required" }) <div class="col-md-4"> @Html.TextBoxFor(model => model.SaleOrderNo, new { @class = "form-control", @readonly = "readonly" }) @Html.ResourceValidationMessageFor(model => model.SaleOrderNo, "", new { @class = "text-danger" }) </div> @Html.ResourceLabelFor(model => model.OrderDate, new { @class = "control-label col-md-2 field-required" }) <div class="col-md-4"> @Html.TextBoxFor(model => model.OrderDate, new { @class = "form-control datepicker" }) @Html.ResourceValidationMessageFor(model => model.OrderDate, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-4"> <input type="submit" value="@this.Intl("Common.Save").ToString()" class="btn btn-primary" /> <input type="submit" name="SaveAndSubmit" value="@this.Intl("Common.SaveAndSubmit").ToString()" class="btn btn-primary" /> @Html.ActionLink(this.Intl("Common.Cancel").ToString(), "SalesOrderList", null, new { @class = "btn btn-default" }) </div> </div> </div> }
Controller层代码,获取某ID销售数据:
public ActionResult SalesOrderEdit(int saleOrderID) { SaleOrder saleOrder = _saleOrderService.FindSaleOrder(saleOrderID); if (saleOrder == null) { return HandError(); } if (!saleOrder.IsRetail) { return RedirectToAction("DisSalesOrderEdit", new { saleOrderID = saleOrderID }); } saleOrder.Customer = _basicDataService.GetCustomerByCode(saleOrder.CustormerCode); saleOrder.Delivery = _basicDataService.GetDeliverierByCode(saleOrder.DeliveryCode); SaleOrderViewModel saleOrderViewModel = saleOrder.ToModel(); //附件 IList<Attachment> attachments = _basicDataService.LoadAttachment(saleOrderViewModel.RefID); saleOrderViewModel.Attachments = new List<AttachmentOrderView>(); foreach (Attachment attachment in attachments) { saleOrderViewModel.Attachments.Add(attachment.ToOrderView()); } return View(saleOrderViewModel); } ``` Controller层代码,编辑某ID销售数据: ``` // <summary> /// 自有业务销售订单表单编辑 Post /// </summary> /// <param name="saleOrder"></param> /// <returns></returns> [HttpPost, NamedFormParameter("SaveAndSubmit", "saveAndSubmit")] [ValidateAntiForgeryToken()] public ActionResult SalesOrderEdit(SaleOrderViewModel saleOrderViewModel, bool saveAndSubmit) { try { saleOrderViewModel.ModifyBy = this.UserName; saleOrderViewModel.ModifyDate = DateTime.Now; if (saleOrderViewModel.Attachments != null) { //附件 foreach (AttachmentOrderView attachmentOrderView in saleOrderViewModel.Attachments) { if (attachmentOrderView.EditStatu == "d") { Utils.DeleteFile(attachmentOrderView.FileName); _basicDataService.RemoveAttachment(attachmentOrderView.AttachmentID); } } } SaleOrder saleOrder = saleOrderViewModel.ToEntity(); IList<Attachment> attachments = new List<Attachment>(); Utils.UploadFileBatch(Request.Files, attachments, saleOrder.RefID); _basicDataService.SaveAttachments(attachments); _saleOrderService.UpdateSaleOrder(saleOrder); return View("Finish", new List<string>() { this.Intl("Common.Message.SaveSuccessfully"), "SalesOrderList" }); } catch (Exception e) { Util.Logger.Error(e.Message, e); return View("Finish", new List<string>() { this.Intl("Common.Message.SaveFailed"), "SalesOrderList" }); } }
还是以销售订单为例,我们删除一个ID的订单,销售列表的删除按钮View层代码:
<a class="delete btn btn-default btn-xs btn-delete" href="#" data-puorderid="@m.SaleOrderID">@this.Intl("Common.Delete").ToHtmlString()</a> javascript代码: <script type="text/javascript"> $(document).ready(function () { $("#salesordertb a.delete").bind("click", function () { if (confirm("@this.Intl("Common.ReConfirmDelete")")) { var data = "saleOrderID=" + $(this).attr("data-saleorderid"); var ajxoptioan = { url: "@Url.Action("SalesOrderDelete")", type: 'Post', async: false, dataType: 'json', data: data, context: this, success: function (result) { if (result.ReMsg == true) { $('#SalesOrderListForm').submit(); } else { ShowNotice(result.ReMsg, "danger"); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { ShowNotice(XMLHttpRequest[1], "danger"); } } $.ajax(ajxoptioan); } }); }); </script> Controller层代码: /// <summary> /// 销售订单 ajax删除 /// </summary> /// <param name="inStoreID"></param> /// <returns></returns> public ActionResult SalesOrderDelete(int saleOrderID) { bool result = false; string message = this.Intl("Common.Message.DeleteFailed"); try { result = this._saleOrderService.RemoveSaleOrder(saleOrderID) > 0; if (result) { this.SuccessNotice(this.Intl("Common.Message.DeleteSuccessfully")); } return Json(new { ReMsg = result }, JsonRequestBehavior.AllowGet); } catch (Exception e) { message += "<br/>" + e.Message; return Json(new { ReMsg = message }, JsonRequestBehavior.AllowGet); } } ``` 文章转载自:华晨软件-[云微学院](http://www.hocode.com/) » [初识MVC框架-
文章转载自:云微平台-云微学院 » 初识MVC框架–Controller与View交互1
本文标题:初识MVC web框架–Controller与View交互1
本文地址:http://www.my-framework.com/OrgTec/Back/0002.html
标签:web,ViewData,TempData,saleOrderViewModel,Controller,MVC,new,model,View 来源: https://www.cnblogs.com/frfwef/p/12516347.html