开发者

Pass a value from controller to view

I have a problem in passing a value from controller to view

In controller, In the edit method

    public ActionResult Edit( FormCollection form)
        {
        var id = Int32.Parse(form["CustomerServiceMappingID"]);

        var datacontext = new ServicesDataContext();
        var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID    == id);
        TryUpdateModel(serviceToUpdate, new string[] { "CustomerID", "ServiceID", "Status" }, form.ToValueProvider());

        if (ModelState.IsValid)
        {
            try
            {
                var qw = (from m in datacontext.Mapings
                          where id == m.CustomerServiceMappingID
                          select m.CustomerID).First();
                ViewData["CustomerID"] = qw;
                datacontext.SubmitChanges();
                //return Redirect("/Customerservice/Index/qw");
                return RedirectToAction("Index", new { id = qw });
            }
            catch{
                }
        }

        return View(serviceToUpdate);
    }

Now in edit's view , I used this

开发者_JAVA技巧
                           @Html.Encode(ViewData["CustomerID"])

This is my Index method

    public ActionResult Index(int id)
    {

        var dc = new ServicesDataContext();
        var query = (from m in dc.Mapings
                   where m.CustomerID == id
                    select m);
       // var a = dc.Customers.First(m => m.CustomerId == id);
       // ViewData.Model = a;
       // return View();
        return View(query);
    }

But the customerID on the page turns to be null.. Can u let me know if this procedure is correct?


You don't need to requery the id. Just use the id directly:

if (ModelState.IsValid)
{
  datacontext.SubmitChanges();
  //return Redirect("/Customerservice/Index/qw");
  return RedirectToAction("Index", new { id = id});
}

Since you are redirecting the ViewData["CustomerID"] will be lost. However the id in your Index method should be valid. If your Index View requires the ViewData["CustomerID"] set it in your Index action:

public ActionResult Index(int id)
{
  ViewData["CustomerID"] = id;
  //....


I'm a bit confused as to which view does not have access to ViewData["CustomerId"]. If it's the Index view, you should set ViewData["CustomerId"] = id there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜