[英]Pass data from one controller action to another view in mvc
我需要將變量從一個控制器動作傳遞到另一視圖中的javascript。
在控制器動作A中:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
TempData["Name"] = "Monjurul Habib";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
在另一個JavaScript中:
function gridA() {
var message = '@TempData["Name"]';
$('#mylabel').text(message);
}
僅臨時數據有效,但從iam調用動作控制器后的第二次起第一次無效
如果您的JavaScript位於采用ProjectViewModelNew的同一視圖內,則可以為視圖使用其他類型,例如,可以使用composition:
public class MyCompositeClass
{
ProjectViewModelNew ProjectViewModel{get;set;};
string Name{get;set;}
}
然后您的操作方法將是:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
var myView = new MyCompositeClass();
try
{
UpdateModel(res);
myView.ProjecViewModel = res;
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
myView.Name= "Monjurul Habib";
}
return View(myView);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(myView);
}
}
和您的js將是:
function gridA() {
var message = '@Model.Name';
$('#mylabel').text(message);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.