Asp.net mvc 2 /应用程序中的服务器错误。找不到资源
我创建了一个ASP.NET MVC应用程序,在创建一个条目之后,当我试图编辑它时遇到了问题;编辑数据库中已有的值可以正常工作,但当我尝试编辑我创建的条目时,会出现以下错误: “/”应用程序中出现服务器错误。 找不到资源。 描述:HTTP404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请检查以下URL并确保其拼写正确 以下是我的控制器编辑和创建操作方法:Asp.net mvc 2 /应用程序中的服务器错误。找不到资源,asp.net-mvc-2,Asp.net Mvc 2,我创建了一个ASP.NET MVC应用程序,在创建一个条目之后,当我试图编辑它时遇到了问题;编辑数据库中已有的值可以正常工作,但当我尝试编辑我创建的条目时,会出现以下错误: “/”应用程序中出现服务器错误。 找不到资源。 描述:HTTP404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请检查以下URL并确保其拼写正确 以下是我的控制器编辑和创建操作方法: public ActionResult Create() {
public ActionResult Create()
{
return View();
}
//
// POST: /Customer/Create
[HttpPost]
public ActionResult Create(Customer cs, bool Ontario, bool IN, bool MA)
{
try
{
ViewData["Ontario"] = Ontario;
ViewData["IN"] = IN;
ViewData["MA"] = MA;
northwndEntities nw = new northwndEntities();
if (ViewData["Ontario"].Equals(true))
{
cs.Region = "Ontario";
}
else
if (ViewData["IN"].Equals(true))
cs.Region = "Indianapolis";
else
if (ViewData["MA"].Equals(true))
cs.Region = "Massachussets";
nw.Customers.AddObject(cs);
nw.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Edit(string id)
{
return View(GetCustomer(id));
}
//
// POST: /Customer/Edit/5
[HttpPost]
public ActionResult Edit(Customer cust, bool ontario, bool IN, bool MA)
{
try
{
ViewData["Ontario"] = ontario;
ViewData["IN"] = IN;
ViewData["MA"] = MA;
northwndEntities nw = new northwndEntities();
if (ViewData["Ontario"].Equals(true))
{
cust.Region = "Ontario";
}
else
if (ViewData["IN"].Equals(true))
cust.Region = "Indianapolis";
else
if (ViewData["MA"].Equals(true))
cust.Region = "Massachussets";
Customer origCust = GetCustomer(cust.CustomerID);
nw.Customers.Attach(cust);
nw.ApplyOriginalValues("Customers", origCust);
nw.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
[NonAction]
public Customer GetCustomer(string id)
{
northwndEntities nw = new northwndEntities();
var cust = from c in nw.Customers
where c.CustomerID == id
select c;
Customer customer = cust.FirstOrDefault();
return customer;
}
问题解决了!在Global.asax中,路由的实现方式如下:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
);
问题是该ID在数据库中定义为nchar(5)。当我在数据库中创建一个新条目时,它应该有一个正好5个字符的CustomerID字段。如果不是(少于5个字符),则结果URL将在CustomerID字段中为每个缺少的字符指定一个%20个字符,从而生成“服务器错误…”
因此,最好使用int-id,这样可以避免不必要的问题。要消除每个缺少字符的%20字符,只需在视图中的route值中添加.Trim():
@Url.Action("Edit", new { id=item.TheIdValue.Trim() }
或
我注意到,在“索引视图”中单击“编辑”时,如果删除%20,浏览器试图获取的url将以(%20%20%20)结尾。。从url和刷新页面,它将显示编辑视图。删除视图也是如此。有什么想法吗,伙计们?
@Html.ActionLink("Edit", "Edit", new { id = item.TheIdValue.Trim() })