[英]Pass data from one controller action to another view in mvc
I require to pass a variable from one controller action to javascript in another view.. 我需要将变量从一个控制器动作传递到另一视图中的javascript。
In controller Action A: 在控制器动作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);
}
}
In another javascript: 在另一个JavaScript中:
function gridA() {
var message = '@TempData["Name"]';
$('#mylabel').text(message);
}
Only Tempdata works But not the first time its working from the second time after iam calling the action controller 仅临时数据有效,但从iam调用动作控制器后的第二次起第一次无效
If your javascript is inside the same view that takes the ProjectViewModelNew, you can use a different type for your view, for example you can use composition: 如果您的JavaScript位于采用ProjectViewModelNew的同一视图内,则可以为视图使用其他类型,例如,可以使用composition:
public class MyCompositeClass
{
ProjectViewModelNew ProjectViewModel{get;set;};
string Name{get;set;}
}
and then your action method would be: 然后您的操作方法将是:
[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);
}
}
and your js would be: 和您的js将是:
function gridA() {
var message = '@Model.Name';
$('#mylabel').text(message);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.