简体   繁体   English

如何将临时数据从部分视图发送到其父视图

[英]How to send temp data from Partial View to its parent View

How to send temp data from Partial View to its parent View? 如何从局部视图向其父视图发送临时数据? I need information about success save to database. 我需要有关成功保存到数据库的信息。 Please example with TempData or HttpContext.Items. 请以TempData或HttpContext.Items为例。 Problem is how to send information about success save between difference View (From partial View to parent View) 问题是如何发送差异视图之间的成功保存信息(从局部视图到父视图)

This is method in Controller 这是控制器中的方法

 [HttpPost]
        [ValidateAntiForgeryToken]
        public PartialViewResult _AddPost(int idOrder, AddPositionViewModel viewModel)
        {
            var findOrder = db.Order.Find(idOrder);

            if (ModelState.IsValid)
            {

                OrderPosition position = new OrderPosition { Description = viewModel.Description };
                db.OrderPosition.Add(position);
                //db.Entry(position).State = System.Data.Entity.EntityState.Unchanged;
                findOrder.OrderPositionList.Add(position);
                db.SaveChanges();
                ViewBag.Information = position;                  

                if (ViewBag.Information != null)
                {
                    TempData["Add-Post"] = string.Format("Odpowiedz użytkownika {0} została dodana!", User.Identity.Name);
                    //HttpContext.Items["Info"] = string.Format("Odpowiedz użytkownika {0} została dodana!", User.Identity.Name);
                }

            }
            Thread.Sleep(2000);
            return PartialView();

        }

//Method Parent View

 public ActionResult ListOrder(int? IdStatusOrder)
        {
            var ListAllOrder = db.Order.ToList();
            var userId = User.Identity.GetUserId();
            var viewodel = new ListOrdersUserViewModel()
            {           
                ListOrdersUser = ListOrders
            };
              };
            return View(viewodel);
        }

And View in MVC 在MVC中查看

@model AplikacjaHelpDesk.ViewModels.ListOrdersUserViewModel
@using AplikacjaHelpDesk.Infrastructure
@{
    ViewBag.Title = "List Orders Users";
    Layout = "~/Views/Shared/_LayoutAdministracja.cshtml";
}

<div class="container-fluid">
    <img src="~/Content/Images/Layout/Home.png" />
    <a href="link">
        @Html.MvcSiteMap().SiteMapPath()
    </a>
    <h2><span class="glyphicon glyphicon-user"></span>&nbsp<strong>List Orders </strong></h2>
    <br /><br />
    <div id="divLoading" class="panel panel-primary text-center text-primary" style="display:none;">
        <h3><strong>Please wait for post!</strong></h3>
    </div>
    <div id="divLoadingForm" class="panel panel-primary text-center text-primary" style="display:none;">
        <h3><strong>Please wait for form</strong></h3>
    </div>
    @if (ViewBag.Information != null)
            {
        <div class="alert alert-warning"><h4><strong>@TempData["Add-Post"]</strong></h4></div>
    }*@

    <table class="table table-responsive table-striped" style="text-combine-upright:all;">
        <tr style="text-transform: uppercase; text-combine-upright:all;">
            <th>
                <label>Numer Order</label>
            </th>
            <th>
                <label>Acceptance Date</label>
            </th>
            <th>
                <label>Date of planned completion of the order</label>
            </th>
            <th>
                <label>Data finish</label>
            </th>
            <th style="width: 160px;"></th>
            <th style="width: 160px;"></th>
        </tr>

        @foreach (var item in Model.ListOrdersUser)
        {

            <tr class="panel panel-primary">
                <td>
                    <h5><strong>Nuber Orders: @Html.DisplayFor(modeItem => item.IdOrder)</strong></h5>
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DateAccept )
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DataPlaningFinish)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.DataFinish)
                </td>
                <td>
                    @Ajax.ActionLink("Show Post Order", "_ListPost", new { idOrder = @item.IdOrder }, new AjaxOptions()
               {
                   HttpMethod = "GET",
                   LoadingElementId = "divLoading",
                   UpdateTargetId = "divPosition",
                   InsertionMode = InsertionMode.Replace

               }, new { @class = "btn btn-primary" })
                </td>
                <td>


                    @Ajax.ActionLink("Add Answer", "_AddPost", new { idZlecenia = @item.IdZlecenia }, new AjaxOptions()
               {
                   HttpMethod = "GET",
                   LoadingElementId = "divLoadingForm",
                   UpdateTargetId = "divAddPozycje",
                   InsertionMode = InsertionMode.Replace

               }, new { @class = "btn btn-primary" })
                </td>

            </tr>
            ...
            <tr id="divAddPozycje"></tr>
        }
    </table>

</div>

And PartialView - Form 和PartialView-表格

@model AplikacjaHelpDesk.ViewModels.AddPositionViewModel

@{
    ViewBag.Title = "Add Post";
    Layout = null;
}

<link href="~/Content/font-awesome.min.css" rel="stylesheet" />
<script src="~/Scripts/tinymce/tinymce.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/jquery-2.2.3.min.js"></script>




<div class="container-fluid" >
    @using (Ajax.BeginForm(new AjaxOptions()
        {
            UpdateTargetId = "divformResult",
            HttpMethod = "Post"

    }))


    {
        @Html.AntiForgeryToken()
        @Html.Hidden("IdOrder")
        <div class="form-horizontal">
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-1" })
                <div class="col-md-10" >
                    @Html.TextAreaFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10 ">
                    <input type="submit" value="Send" class="btn btn-danger" id="formularz"/>
                </div>
            </div>
        </div>
    }

</div>

        @*@if (TempData["Add-Post"] != null)
        {

            <div class="alert alert-warning">
                <h4><strong>@TempData["Add-Post"];</strong></h4>
            </div>
        }*@


<script type="text/javascript">
    tinymce.init({
        selector: "textarea",
        language: "pl",
        theme: "modern",
        fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48pt 72pt",
        plugins: [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table contextmenu paste",
            "textcolor",
            "colorpicker",

        ],
        theme_advanced_fonts: "Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;AkrutiKndPadmini=Akpdmi-n",

        extended_valid_elements: 'i[class]',
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | forecolor backcolor | fontsizeselect"
    });


</script>

Implement a GET version of _AddPost that returns the TempData value: 实现_AddPostGET版本,该版本返回TempData值:

[HttpGet]
[ValidateAntiForgeryToken]
public JsonResult _AddPost()
{
    return Json(TempData["Add-Post"]);
}

Modify your original ActionLink and add an OnComplete function: 修改原始的ActionLink并添加一个OnComplete函数:

@Ajax.ActionLink("Add Answer", "_AddPost", new { idZlecenia = @item.IdZlecenia }, new AjaxOptions()
{
    HttpMethod = "POST", // Not "GET"
    LoadingElementId = "divLoadingForm",
    UpdateTargetId = "divAddPozycje",
    InsertionMode = InsertionMode.Replace,
    OnComplete = "updateMyAlert();" // Add this

}, new { @class = "btn btn-primary" })

Follow that with a new ActionLink that updates my-alert-text element: 在此之后,添加一个新的ActionLink来更新my-alert-text元素:

@Ajax.ActionLink("", "_AddPost", new {}, new AjaxOptions()
{
    HttpMethod = "GET",
    UpdateTargetId = "my-alert-text",
    InsertionMode = InsertionMode.Replace,
    OnSuccess = "showMyAlertIfNeeded();"

}, new { id = "update-my-alert-action-link" })

Complement the above with relevant HTML and JavaScript: 用相关的HTML和JavaScript补充以上内容:

<div class="alert alert-warning" id="my-alert" style="display: none;">
    <h4><strong id="my-alert-text"></strong></h4>
</div>
<script>
    function updateMyAlert() {
        document.getElementById("update-my-alert-action-link").click();
    }
    function showMyAlertIfNeeded() {
        var display = document.getElementById("my-alert-text").text ? "" : "none";
        document.getElementById("my-alert").style.display = display;
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM