C# 错误:参数字典包含参数';id';不可为空的类型

C# 错误:参数字典包含参数';id';不可为空的类型,c#,asp.net-mvc,C#,Asp.net Mvc,尝试使用搜索时出现错误。这是我的错误: 参数字典包含“MvcSimpleModelBinding.Controllers.PersonController”中“System.Web.Mvc.ActionResult Trazi(Int32)”方法的不可为null类型“System.Int32”的参数“id”的null条目。可选参数必须是引用类型、可为null的类型或声明为可选参数 这是我的控制器: public class PersonController : Controller {

尝试使用搜索时出现错误。这是我的错误:

参数字典包含“MvcSimpleModelBinding.Controllers.PersonController”中“System.Web.Mvc.ActionResult Trazi(Int32)”方法的不可为null类型“System.Int32”的参数“id”的null条目。可选参数必须是引用类型、可为null的类型或声明为可选参数

这是我的控制器:

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

这个错误意味着搜索请求中没有
id
参数,这就是为什么MVC甚至不能调用action方法的原因

现在,让我们找出请求错误的原因。让我们看看我们在视图中看到了什么:

@using (Html.BeginForm("Search", "Person",FormMethod.Get))
{    
    <form>
        Title: @Html.TextBox("id");
        <input type="submit" name="name" value="Search"/>
    </form>   
}
这是一个问题,因为HTML不支持嵌套表单。要修复此问题,您应该使用以下方法删除内部的额外
标记:

@using (Html.BeginForm("Search", "Person",FormMethod.Get))
{    
    Title: @Html.TextBox("id");
    <input type="submit" name="name" value="Search"/>   
}
@使用(Html.BeginForm(“搜索”、“人”、FormMethod.Get))
{    
标题:@Html.TextBox(“id”);
}
您的问题就在这里

public ActionResult Search(int id)
您为该操作设置了一个参数,因此每次输入该操作时都需要一个参数:int id。例如,如果您从另一个页面(例如索引)输入相应的视图页面(即搜索页面),则您需要做的是将您的ruote值与原始URL一起带入。以下是我的例子:

另一种观点:

@Html.ActionLink("Search", "Home", new { id = 2 })

该示例实际上等于/Home/Search/2,这是格式,/[Controller]/[Action]/[Route value],因此您不会再次出现错误。

您正在尝试的URL是什么?您的嵌套表单是无效的html(首先根据您的路由删除内部的
标记),您应该像这样访问
search
操作方法
/search/101
,其中101可以替换为任何有效的int32值。感谢您的回复,但现在我有另一个错误:值不能为null。参数名称:id..我不知道如何解决此错误
@using (Html.BeginForm("Search", "Person",FormMethod.Get))
{    
    Title: @Html.TextBox("id");
    <input type="submit" name="name" value="Search"/>   
}
public ActionResult Search(int id)
@Html.ActionLink("Search", "Home", new { id = 2 })