添加新对象,表单创建



我正在开发一个应用程序,它应该能够创建一个新对象,我的方法必须能够接受输入的数据。我在添加代码以将新的 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);
}

如果我正确理解您的问题,您希望为Model.Id字段分配一个新的 guid。根据您的代码,您似乎正在请求中传递 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。

最新更新