【问题标题】:access tempdata in javascript in mvc4在 mvc4 中的 javascript 中访问 tempdata
【发布时间】:2013-03-25 05:19:33
【问题描述】:

我正在尝试使用 Javascript 访问 TempData。但得到空值。 我正在进行 ajax 调用以更新记录,并且我想显示记录更新成功消息。这将来自控制器的 UpdateOperation 操作。 但目前它将显示空值。我还检查了 Firebug,它显示如下:

function onComplete(e) {

if (e.name == "update") {

alert('');

} 

这是我的控制器代码

 public class OperationController : BaseController
    {
        /// <summary>
        /// Index action will return template view of the page without data
        /// </summary>
        /// <returns>Blank Action</returns>
        public ActionResult Index()
        {
            return this.View();
        }

        /// <summary>
        /// Get all Operation from System
        /// </summary>
        /// <returns>return action result</returns>
        [GridAction]
        public ActionResult SelectOperation()
        {
            IEnumerable<OperationEntity> operationList = OperationComponent.GetAll();
            return this.View(new GridModel(operationList));
        }

        /// <summary>
        /// Method for update operation
        /// </summary>
        /// <param name="entity">moduleViewModel to update Module</param>
        /// <returns>return action result</returns>
        [GridAction]
        public ActionResult UpdateOperation(OperationEntity entity)
        {
            if (ModelState.IsValid)
            {
                entity.Log = new BusinessCore.BusinessEntities.LogDetails();
                entity.Log.ModifiedBy = SessionHelper.UserId;
                Status status = OperationComponent.Update(entity);
                this.TempData["AlertMessage"] = status.Message;
                this.ViewData["_AlertMessage"] = status.Message;
                return this.View(new GridModel(OperationComponent.GetAll()));
            }
            else
            {
                return this.View(entity);
            }
        }
    }

在我看来

@using Telerik.Web.Mvc.UI;
@{
    ViewBag.Title = "Operation List";
}

<h2>@ViewBag.Title</h2>
<script src="../../../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
//    function onSave(e) {
//        alert('Record Save Succesfully');
//    }
    function onComplete(e) {
        if (e.name == "update") {
           alert('@TempData["AlertMessage"]');
            alert('@ViewData["_AlertMessage"]');
        }
        if (e.name == "insert") {
            alert("Operation Inserted Successfully");
        }
        if (e.name == "delete") {
            alert("Operation Deleted Successfully");
        }
    }
    function newAlert(type, message) {
    if (message != "" || message != null) {
        $("#alert-area").append($("<div class='alert alert-success " + type + " fade in' data-alert><p><b> " + message + " </b></p></div>"));
        $(".alert-success").delay(4000).fadeOut("slow", function () { $(this).remove(); });
    }
}
</script>

@(Html.Telerik().Grid<QuexstERP.BusinessCore.BusinessEntities.SysAdmin.OperationEntity>()
        .Name("Grid")
         .DataKeys(keys => 
        {
            keys.Add(p => p.Id);
        })
                    .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.Image).ImageHtmlAttributes(new { style = "margin-left:0", title = "Add" }))
        .DataBinding(dataBinding =>
        {
            dataBinding.Ajax()
                .Select("SelectOperation", "Operation")
                .Insert("InsertOperation", "Operation")
                .Update("UpdateOperation", "Operation")
                .Delete("DeleteOperation", "Operation");
        })
        .Columns(columns =>
        {
            columns.Command(commands =>
            {
                commands.Edit().ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Edit" });
                commands.Delete().ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Delete" });
            }).Width(80).Title("Commands");
            columns.Bound(p => p.Name).Width(200).Title("Operation Name");
            columns.Bound(p => p.Description).Width(310).Title("Description");
        })
        .ClientEvents(events => events
                .OnComplete("onComplete")
                )
                    .Editable(editing => editing.Mode(GridEditMode.PopUp).InsertRowPosition(GridInsertRowPosition.Top))

        .Pageable()
        .Scrollable()
        .Sortable()
        .Filterable()        
)
@section HeadContent {
<style type="text/css">
    .field-validation-error
    {
        position: absolute;
        display: block;
    }

    * html .field-validation-error { position: relative; }
    *+html .field-validation-error { position: relative; }

    .field-validation-error span
    {
        position: relative;
        white-space: nowrap;
        color: red;
        padding: 10px 5px 3px;
        background: transparent url('@Url.Content("~/Content/Common/validation-error-message.png") ') no-repeat 0 0;
    }

    /* in-form editing */
    .t-edit-form-container
    {
        width: 480px;
        margin: 1em;
    }

    .t-edit-form-container .editor-label,
    .t-edit-form-container .editor-field
    {
        padding-bottom: 1em;
        float: left;
    }

    .t-edit-form-container .editor-label
    {
        width: 25%;
        text-align: right;
        padding-right: 3%;
        clear: left;
    }
    .t-edit-form-container .editor-field textarea
    {
    font-size:11px;
    width:80%;
}
    .t-edit-form-container .editor-field
    {
        width: 70%;
    }
</style>
}

【问题讨论】:

  • 尝试在获取 e.name=="update" 的 if 语句中放置 debugger; 并检查它是否涉及调试器
  • 是的,我已经做到了。它来了,但是 alert('');值为 null 因为我正在对服务器进行 AJAX 调用。它在 Tempdata 中得到了计算,但它没有刷新 Javascript 的值

标签: javascript asp.net-mvc asp.net-mvc-4 tempdata


【解决方案1】:

我知道这是一个老问题,但我想我会回答,因为我正在寻找完全相同的解决方案,并希望能帮助其他人。

这解决了我how-to-get-the-tempdata-in-javascript

基本上,您的语法缺少括号

    //Your code
alert('@TempData["AlertMessage"]');

// Correct code
alert('@(TempData["AlertMessage"])');

@后面的括号

希望这对像我这样的下一个搜索者有所帮助。

【讨论】:

    【解决方案2】:

    TempData 用于重定向到操作。试试ViewBag

    在控制器中:

    ViewBag.AlertMessage = status.Message;
    

    在视图中:

    @{
        ViewBag.Title = "Operation List";
        string alert = "Your custom error message";
    
        if(ViewBag.AlertMessage != null)
        {
            alert = (string)ViewBag.AlertMessage;
        }        
    }
    

    和javascript

    var jsAlert = '@alert';
    alert(jsAlert );
    

    【讨论】:

    • 您的回答似乎很聪明,但我收到错误消息“当前上下文中不存在名称 'alert'”。另一方面,使用 Html.BeginForm,我可以使用 TempData 或 ViewBag 将消息从 Controller 传递到 View。但是对于阿贾克斯,我无法通过。那么,您的答案解决了这个问题吗?或者应该应用哪些更改?提前致谢。
    • 您会收到此错误(“当前上下文中不存在名称 'alert'”),因为 'alert' 变量应该与 js 代码和视图顶部位于同一页面中。其次,你想用ajax将数据从控制器传递到视图还是从视图传递到控制器?我不能很好地回答问题。
    • 我想将数据从控制器传递到视图。另一方面,最好在答案中输入必要的变量,以便其他没有足够经验的人可以轻松使用它们。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 2021-09-03
    • 2021-09-13
    • 2012-07-25
    • 2021-10-16
    • 1970-01-01
    相关资源
    最近更新 更多