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

时间:2013-04-13 14:17:30

标签: javascript asp.net-mvc-4

我需要将一个变量从一个控制器动作传递到另一个视图中的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);
}

只有Tempdata有效但不是第一次在iam调用动作控制器后第二次工作

  1. 我希望第一次使用临时数据
  2. 使用
  3. 后我想清除数据

1 个答案:

答案 0 :(得分:1)

如果您的javascript位于采用ProjectViewModelNew的同一视图中,则可以为视图使用不同的类型,例如,您可以使用合成:

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);
}
相关问题