【问题标题】:parameter problem in asp.net mvcasp.net mvc中的参数问题
【发布时间】:2011-06-09 03:29:33
【问题描述】:

我是 asp.net mvc 的新手。我有带参数 id 的索引方法:

 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);
    }

现在,当我尝试从编辑重定向到索引时,我收到一个错误“参数字典包含方法'System.Web.Mvc.ActionResult'的不可空类型'System.Int32'的参数'id'的空条目'MVCServices.Controllers.CustomerserviceController' 中的 Index(Int32)'。可选参数必须是引用类型、可空类型或声明为可选参数。

   [HttpPost]
    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();
                datacontext.SubmitChanges();
                //return Redirect("/Customerservice/Index/qw");
                return RedirectToAction("Index", new { qw = qw });
            }
            catch{
                }
        }

        return View(serviceToUpdate);
    }

这是视图:

                 @Html.ActionLink("Back to List", "Index")

Index 方法中的 id 原来是从另一个控制器获取的 customerid,而 Edit 中的 id 来自另一个表。您能告诉我我一直在做的错误以及如何解决它吗?

【问题讨论】:

    标签: asp.net-mvc html.actionlink


    【解决方案1】:

    Edit 操作中执行此操作:

    return RedirectToAction("Index", new { id = qw });
    

    【讨论】:

    • 嘿。还有一件事是我有一个链接可以返回cshtml,即视图......所以,你能告诉我如何在视图中使用控制器中的相同变量
    • 您想将哪个变量传递给视图?以及哪种操作方法?
    • 应该看到相同的 qw 值
    • 只需将值添加到视图控制器中的 ViewData 集合中,然后在视图中执行@Html.ActionLink("Back to List", "Index", new { id = ViewData["qw"])
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多