【发布时间】:2018-11-24 00:46:20
【问题描述】:
尝试使用搜索时出错。这是我的错误:
参数字典包含“MvcSimpleModelBinding.Controllers.PersonController”中方法“System.Web.Mvc.ActionResult Trazi(Int32)”的不可为空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。
这是我的控制器:
public class PersonController : Controller {
public ActionResult Search(int id)
{
var mm = DataBase.getById(id);
return View(mm);
}
}
我的班级数据库:
public class DataBase
{
private static List<Person> people = new List<Person>();
private static int _nextId = 1;
public static List<Person> getAll() {
return people;}
public static Person getById(int id)
{
var buscar = people.Find(x => x.Id == id);
if (buscar == null)
{
throw new ArgumentNullException("id");
}
return buscar;}
查看
@using (Html.BeginForm("Search", "Person",FormMethod.Get))
{
<form>
Title: @Html.TextBox("id");
<input type="submit"
name="name"value="Search"/>
</form>
}
<p>@Html.ActionLink("Create New",
"Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>@Html.DisplayNameFor(model =>
model.Name)
</th>
<th>@Html.DisplayNameFor(model =>
model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Street)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.State)
</th>
<th>
@Html.DisplayNameFor(model => model.Zipcode)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Street)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.State)
</td>
<td>
@Html.DisplayFor(modelItem => item.Zipcode)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
路由:
public class RouteConfig{
public static void
RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
【问题讨论】:
-
你尝试的 URL 是什么?
-
您的嵌套表单是无效的 html(首先删除内部的
<form>标签) -
根据您的路由,您应该访问像
/search/101这样的search操作方法,其中 101 可以替换为任何有效的 int32 值。
标签: c# asp.net-mvc