在mvc4中访问javascript中的临时数据
我正在尝试用Javascript访问TempData。但是得到空值。 我正在进行ajax调用以更新记录,我希望显示记录已成功更新的消息。这将来自控制器的UpdateOperation操作。 但当前它将显示空值。我还检查了Firebug,它显示如下:在mvc4中访问javascript中的临时数据,javascript,asp.net-mvc,asp.net-mvc-4,tempdata,Javascript,Asp.net Mvc,Asp.net Mvc 4,Tempdata,我正在尝试用Javascript访问TempData。但是得到空值。 我正在进行ajax调用以更新记录,我希望显示记录已成功更新的消息。这将来自控制器的UpdateOperation操作。 但当前它将显示空值。我还检查了Firebug,它显示如下: function onComplete(e) { if (e.name == "update") { alert(''); } 这是我的控制器代码 public class OperationController : BaseContro
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);
}
}
}
公共类操作控制器:BaseController
{
///
///索引操作将返回没有数据的页面的模板视图
///
///空白动作
公共行动结果索引()
{
返回这个.View();
}
///
///从系统获取所有操作
///
///返回操作结果
[行动]
公共操作结果SelectOperation()
{
IEnumerable operationList=OperationComponent.GetAll();
返回此.View(新的GridModel(operationList));
}
///
///更新操作的方法
///
///moduleViewModel以更新模块
///返回操作结果
[行动]
公共操作结果更新操作(OperationEntity实体)
{
if(ModelState.IsValid)
{
entity.Log=新的BusinessCore.BusinessEntities.LogDetails();
entity.Log.ModifiedBy=SessionHelper.UserId;
状态状态=操作组件。更新(实体);
this.TempData[“AlertMessage”]=status.Message;
this.ViewData[“_AlertMessage”]=status.Message;
返回this.View(新的GridModel(OperationComponent.GetAll());
}
其他的
{
返回此.视图(实体);
}
}
}
在我看来
@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>
}
@使用Telerik.Web.Mvc.UI;
@{
ViewBag.Title=“操作列表”;
}
@视图包。标题
//函数onSave(e){
//警报(“记录保存成功”);
// }
功能完成(e){
如果(例如名称=“更新”){
警报('@TempData[“AlertMessage”]');
警报('@ViewData[“_AlertMessage”]');
}
如果(如名称=“插入”){
警报(“操作插入成功”);
}
如果(例如,名称=“删除”){
警报(“操作已成功删除”);
}
}
函数newAlert(类型、消息){
如果(消息!=“”| |消息!=null){
$(“#警报区”)。追加($(“”+消息+“”);
$(“.alert success”).delay(4000.fadeOut(“slow”,function(){$(this.remove();});
}
}
@(Html.Telerik().Grid())
.名称(“网格”)
.DataKeys(keys=>
{
key.Add(p=>p.Id);
})
.ToolBar(commands=>commands.Insert().ButtonType(GridButtonType.Image).ImageHtmlAttributes(新的{style=“margin left:0”,title=“Add”}))
.DataBinding(数据绑定=>
{
Ajax()
.选择(“选择操作”、“操作”)
.插入(“插入操作”、“操作”)
.Update(“更新操作”、“操作”)
.删除(“删除操作”、“操作”);
})
.列(列=>
{
columns.Command(commands=>
{
commands.Edit().ButtonType(GridButtonType.Image).HtmlAttributes(新的{title=“Edit”});
commands.Delete().ButtonType(GridButtonType.Image).HtmlAttributes(新的{title=“Delete”});
}).宽度(80)。标题(“命令”);
columns.Bound(p=>p.Name).Width(200).Title(“操作名”);
columns.Bound(p=>p.Description).Width(310).Title(“Description”);
})
.ClientEvents(事件=>事件
.OnComplete(“OnComplete”)
)
.Editable(editing=>editing.Mode(GridEditMode.PopUp).InsertRowPosition(GridInsertRowPosition.Top))
.Pageable()
.Scrollable()
.Sortable()
.可过滤()
)
@章节标题内容{
.字段验证错误
{
位置:绝对位置;
显示:块;
}
*字段验证错误{position:relative;}
*+字段验证错误{position:relative;}
.字段验证错误范围
{
位置:相对位置;
空白:nowrap;
颜色:红色;
填充:10px 5px 3px;
背景:透明url('@url.Content(“~/Content/Common/validation error message.png”))不重复0;
}
/*表单编辑*/
.t-edit-form-container
{
宽度:480px;
边缘:1米;
}
.t-edit-form-container.editor标签,
.t-edit-form-container.editor字段
{
垫底:1米;
浮动:左;
}
.t-edit-form-container.editor标签
{
宽度:25%;
文本对齐:右对齐;
右:3%;
清除:左;
}
.t-edit-form-container.editor字段文本区域
{
字体大小:11px;
宽度:80%;
}
.t-edit-form-container.editor字段
{
宽度:70%;
}
}
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 );
我知道这是一个老问题,但我想我会回答,因为我正在寻找完全相同的解决方案,希望能帮助其他人 这为我解决了问题 本质上,您的语法缺少括号
//Your code
alert('@TempData["AlertMessage"]');
// Correct code
alert('@(TempData["AlertMessage"])');
后面的括号@
希望这能帮助下一个像我这样的搜索者。尝试放置
调试器代码>在你的if语句中,它获取e.name==“update”,并检查它是否到达调试器。我已经这样做了;值为null,因为我正在对服务器进行AJAX调用。它在Tempdata中得到calue,但它不是刷新JavaScription的值。您的回答似乎很聪明,但我得到一个错误“t中不存在名称'alert'