簡體   English   中英

返回PartialView時在腳本中使用TempData

[英]Using TempData inside scripts when returning a PartialView

我正在嘗試將TempData值傳遞給我的視圖,但是我的控制器動作是ajax發布控制器,並返回了partialview。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CategoryViewModel model)
{
    if (ModelState.IsValid)
    {
        var category = new Category()
        {
            Name = model.Name,
            Description = model.Description
        };
        //test
        System.Threading.Thread.Sleep(2000);

        try
        {
            _repository.AddCategory(category);

            TempData["success"] = string.Format("Category Added");
            return PartialView("~/Areas/Dashboard/Views/Category/_List.cshtml", CategoryListMap());
        }
        catch(Exception ex)
        {
            TempData["error"] = string.Format("{0}", ex);
            return PartialView("~/Areas/Dashboard/Views/Category/_List.cshtml", CategoryListMap());
        }
    }

    TempData["error"] = string.Format("Modal state is not valid");
    return PartialView("~/Areas/Dashboard/Views/Category/_List.cshtml", CategoryListMap());
}

我的創建表單局部視圖:

@using (Ajax.BeginForm("Create", "Category", new { area = "dashboard" }, new AjaxOptions { UpdateTargetId = "categories", OnComplete = "onComplete", OnBegin = "onBegin" }))
{
    @Html.AntiForgeryToken()
    <div class="modal-body">
        <div class="form-group">
            @Html.LabelFor(m => m.Name)
            @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.Name)
        </div>
        <div class="form-group">
            @Html.LabelFor(m => m.Description)
            @Html.TextAreaFor(m => m.Description, new { @class = "form-control", rows = "5" })
            @Html.ValidationMessageFor(m => m.Description)
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
        <button class="ladda-button btn btn-primary" type="submit" data-style="zoom-in">Add</button>
    </div>
}

因此,由於ajax形式,我的控制器必須返回一個partialview,並且將TempData值傳遞給_listpartialview

@if (TempData["error"] != null)
{
    <p>
        <div class="alert alert-danger alert-dismissable">
            <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
            @TempData["error"]
        </div>
    </p>
}
@if (TempData["success"] != null)
{
    <p>
        <div class="alert alert-success alert-dismissable">
            <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
            @TempData["success"]
        </div>
    </p>
}

<table class="table table-striped table-bordered table-hover dataTables">
    <thead>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var category in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(m => category.CategoryId)
                </td>
                <td>
                    @Html.DisplayFor(m => category.Name)
                </td>
                <td>
                    @Html.DisplayFor(m => category.Description)
                </td>
            </tr>
        }
    </tbody>
    <tfoot>
        <tr>
            <th>#</th>
            <th>Name</th>
            <th>Description</th>
        </tr>
    </tfoot>
</table>

如您所見,我在我的partialview中獲取了TempData值,一切工作正常,但是我遇到的問題是如何在我的視圖中獲取TempData值? 我試圖在視圖本身內部獲取TempData值,但它不起作用,因為我認為在控制器中我正在返回一個partialview,而TempData值僅在請求partialview時才會顯示?

這是我的全貌:

<div class="row wrapper border-bottom white-bg page-heading">
    <div class="col-lg-10">
        <h2>Categories</h2>
        <ol class="breadcrumb">
            <li>
                <a href="@Url.Action("Index", "Category")">Categories</a>
            </li>
            <li class="active">
                <strong>List</strong>
            </li>
        </ol>
    </div>
    <div class="col-lg-2">
    </div>
</div>
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal1">
                        <i class="fa fa-plus"></i>
                    </button>
                </div>

                <div class="ibox-content table-responsive">
                    <div id="categories">
                        @{Html.RenderAction("List", "Category", new { area = "dashboard" });}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal inmodal" id="myModal1" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content animated fadeIn">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">Add a category</h4>
            </div>
            @{ Html.RenderAction("Create", "Category", new { area = "dashboard" });}
        </div>
    </div>
</div>

@section Scripts {
    @Scripts.Render...blahblah

    <script type="text/javascript">

        function onSuccess() {
            //remove toastr
            toastr.remove();
            **//not working, tempdata value not set**
            toastr.success('@TempData["success"]', 'Success');
        }

        function onFailure() {
            //remove toastr
            toastr.remove();
            **//not working, tempdata value not set**
            toastr.error('@TempData["error"]', 'Error');
        }
    </script>
}

如果我嘗試在完整視圖中使用TempData值,則未設置任何值...我無法在PartialView中呈現腳本,並且據我了解,您也不應在PartialView中編寫任何腳本, 所以我該如何使用返回帶有tempdata的部分視圖時腳本中的tempdata值???

您不適合使用TempData (這是用於在控制器方法之間傳遞數據),並且對於將數據從控制器傳遞到視圖,您應該使用ViewBagViewData (或者更好的是,在視圖模型中使用屬性)。

但是問題是您進行了ajax調用,以接收控制器創建的部分視圖的html。 您不會將TempData["error"]TempData["success"]的值發送回客戶端,而只是將部分視圖的html發送回客戶端。

您可以通過將消息添加到ViewBag屬性來完成此操作

ViewBag.Message = "...."; // your success or error message

在局部視圖中,創建一個隱藏的輸入來存儲值

<input type="hidden" id="message" value="@ViewBag.Message" />

並且在ajax成功回溯中,您可以使用

success: function(data) {
    $('someElement').append(data); // append the partial view to the DOM
    var message = $('#message').val(); // get the value of the message
    toastr.success(message , 'Success'); // display it
}

但是,返回整個表的一部分並在視圖中替換它不是很有效,您應該考慮進行ajax調用以保存數據,然后返回json表示成功或其他,然后僅基於添加一個新表ros表單中的值。 請參考此DotNetFiddle示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM