首页 > 解决方案 > 添加新对象,创建表单

问题描述

我正在开发一个应该能够创建新对象的应用程序,我的方法必须能够接受输入的数据。我在添加代码以将新的 guid 值分配给我的 id 属性并为每个新的汽车类对象初始化服务属性时遇到问题。
我的控制器代码:

[HttpPost]
Public ActionResult Create(Guid?Id,Car model)
{
    If(ModelState.IsValid)
    {
        bookingList=GetBookings();
        model.Id=bookingList.Count+1;
        bookingList.Add(model);
        TempData["bookingList"]= bookingList;
        return RedirectToAction("Index");
    }
    return View(model);
}

标签: c#asp.net-mvc

解决方案


如果我正确理解你的问题,你想为你的Model.Id领域分配一个新的指导。根据您的代码,您似乎在请求中传递 guid 即Guid? Id

假设上面,您可以尝试以下代码:

[HttpPost]
Public ActionResult Create(Guid? Id, Car model)
{
    If(ModelState.IsValid)
    {
       bookingList=GetBookings();
       model.Id= Id ?? Guid.NewGuid();
       bookingList.Add(model);
       TempData["bookingList"]= bookingList;

       return RedirectToAction("Index");
    }

    return View(model);
    }
}

在这里,行将model.Id= Id ?? Guid.NewGuid();分配您在请求中传递的 Id,否则它将分配新的 GUID。


推荐阅读