简体   繁体   English

将数据从一个控制器动作传递到MVC中的另一个视图

[英]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调用动作控制器后的第二次起第一次无效

  1. I want to temp data to work rom the first time 我想临时将数据临时工作
  2. I want t clear the data after using 我不想在使用后清除数据

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM