access tempdata in javascript in mvc4
Asked Answered
G

2

9

I am trying to access TempData in Javascript. but getting null value. I am making ajax call to Update the record and i want to display Record updated succesfully message. which will come from UpdateOperation action from the controller. but currently it will display null value. I also check with Firebug it shows as follows:

function onComplete(e) {

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

alert('');

} 

Here is my code of controller

 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);
            }
        }
    }

In my view

@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>
}
Golf answered 25/3, 2013 at 5:19 Comment(2)
try placing a debugger; in your if statement which gets e.name=="update" and check whether it comes to the debugger or notDiller
yap i already done that.it is coming but alert(''); value is null As i am doing AJAX call to server. It gets calue in Tempdata but it is not refreshing value of JavascriptGolf
M
28

I know it's an old question but I thought I'd answer as I was looking for the exact same solution and hopefully help some others out.

This solved it for me how-to-get-the-tempdata-in-javascript

Essentially, Your syntax is missing parenthesis

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

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

The parenthesis after the @

Hope this helps the next searcher like me.

Marilee answered 6/5, 2015 at 12:46 Comment(0)
L
3

TempData used when redirect to action. Try ViewBag.

In controller:

ViewBag.AlertMessage = status.Message;

In view:

@{
    ViewBag.Title = "Operation List";
    string alert = "Your custom error message";

    if(ViewBag.AlertMessage != null)
    {
        alert = (string)ViewBag.AlertMessage;
    }        
}

and javascript

var jsAlert = '@alert';
alert(jsAlert );
Limewater answered 25/7, 2013 at 10:21 Comment(3)
Your answer seems to be smart, but I get an error "The name 'alert' does not exist in the current context". On the other hand, with Html.BeginForm I could pass messages from Controller to View by using TempData or ViewBag. But with Ajax, I cannot pass. So, your answer solves this problem? Or which changes should be applied? Thanks in advance.Mongoose
you get this error ("The name 'alert' does not exist in the current context") because, 'alert' variable should be in same page with js code and top of view. Second, do you want to pass data from controller to view or from view to controller with ajax? I can't get question well.Limewater
I want to pass data from Controller to View. On the other hand, it would be better to type necessary variables in your answer so that the other people who do not enough experience can easily use them. Thanks.Mongoose

© 2022 - 2024 — McMap. All rights reserved.