问题描述
|
我是ASP.NEt MVC的新手。我一直在尝试创建新的数据库记录。
public ActionResult Create()
{
var model = new Maping();
return View(model);
}
//
// POST: /Customerservice/Create
[HttpPost]
public ActionResult Create([Bind(Exclude=\"CustomerServiceMappingID\")] Maping servicetoCreate)
{
if (!ModelState.IsValid)
return View();
var dc = new ServicesDataContext();
String s = servicetoCreate.ServiceID.ToString();
if (String.IsNullOrEmpty(s))
ModelState.AddModelError(\"ServiceID\",\"ServiceID is required!\");
dc.Mapings.InsertOnSubmit(servicetoCreate);
dc.SubmitChanges();
return RedirectToAction(\"Index\",\"Home\");
}
因此,我需要做的是我需要ServiceID成为强制性的...我尝试使用的次数不多。所以,你能帮我吗?
另外,我需要将表的另一列客户ID发送回Index方法。
解决方法
如果ServiceId是整数,则应该自动需要它。否则,可以将此属性放在模型类的ServiceId上。
[需要]
public string ServiceId {get; set;} //假设您使用的是字符串
您可以发布模型吗?
, 两件事情 ...
1)
您需要在数据库模型中添加Is Null = false,以便在DataContext尝试保存新记录时,如果设置了这些属性,它将创建一个新ID,或者您需要提供一个。
2)
向您的映射模型添加一个属性,该属性告诉MVC您在“创建操作”中引发的错误。
[Required]
public int ServiceID // <- replace with the correct type.
如果您的索引操作是这样的...
public ActionResult Index(int customerID),then you can send it with the RedirectToAction.
new { customerId = /* insert ID here */ }
我相信是该方法调用中的第三个参数。