返回PartialView

时间:2016-05-06 02:42:55

标签: javascript asp.net ajax asp.net-mvc partial-views

我正在尝试将TempData值传递给我的视图,但我的控制器操作是一个ajax post控制器并返回一个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形式,并且值TempData传递给_list partialview

@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>

正如您所看到的,我在部分视图中获得了TempData值,一切正常,但我遇到的问题是如何在我的视图中获取TempData值? I试图在视图本身内获取TempData值,但它不起作用,因为我认为在我的控制器中我返回了一个部分视图,而TempData值只会在请求部分视图时显示?

以下是我的全部观点:

<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值,则不设置任何值...我无法在部分视图中呈现脚本,根据我的理解,您不应该在部分视图中编写任何脚本,那么当我返回带有tempdata的局部视图时,如何在脚本中使用tempdata值?

1 个答案:

答案 0 :(得分:1)

使用TempData不合适(用于在控制器方法之间传递数据),并且为了将数据从控制器传递到视图,您应该使用ViewBag或{{1} (或者更好的是,视图模型中的属性)。

但问题是你做了一个ajax调用,它接收你的控制器创建的局部视图的html。您没有将ViewDataTempData["error"]的值发送回客户端,只是部分视图的html。

您可以通过将您的消息添加到TempData["success"]属性

来执行此操作
ViewBag

并在局部视图中,创建一个隐藏输入来存储值

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

并且在ajax成功回调中,您可以使用

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

然而,返回整个表的一部分并在视图中替换它并不是非常有效,你应该考虑进行ajax调用以保存数据,然后返回json以指示成功或其他,然后只需附加一个新表ros基于表单中的值。请参阅此DotNetFiddle以获取示例。