,可以通过以下步骤实现:
Order
和Customer
,其中Order
模型类包含一个外键属性CustomerId
,指向Customer
模型类的主键。public class Order
{
public int OrderId { get; set; }
public string OrderName { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}
DropDownListFor
方法生成下拉列表,以选择关联的外键对象。@model Order
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.OrderName)
@Html.TextBoxFor(model => model.OrderName)
@Html.LabelFor(model => model.CustomerId)
@Html.DropDownListFor(model => model.CustomerId, new SelectList(ViewBag.Customers, "CustomerId", "CustomerName"), "Select Customer")
<input type="submit" value="Submit" />
}
public class OrderController : Controller
{
private readonly ApplicationDbContext _context;
public OrderController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
ViewBag.Customers = _context.Customers.ToList();
return View();
}
[HttpPost]
public IActionResult Create(Order order)
{
if (ModelState.IsValid)
{
_context.Orders.Add(order);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
ViewBag.Customers = _context.Customers.ToList();
return View(order);
}
}
Required
属性来确保外键属性的值不为空。public class Order
{
public int OrderId { get; set; }
[Required(ErrorMessage = "Order Name is required.")]
public string OrderName { get; set; }
[Required(ErrorMessage = "Customer is required.")]
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
[Required(ErrorMessage = "Customer Name is required.")]
public string CustomerName { get; set; }
}
这样,在表单提交时,将会进行验证。如果验证失败,将会返回带有错误消息的视图;如果验证成功,将会保存订单并重定向到主页。
这是一个基本的示例,展示了在C# MVC中如何使用外键对象进行表单验证。根据具体的业务需求,可以进一步扩展和优化代码。对于C# MVC开发,腾讯云提供了云服务器、云数据库SQL Server等产品,可以满足开发需求。具体产品信息和介绍可以参考腾讯云官方网站:https://cloud.tencent.com/。
领取专属 10元无门槛券
手把手带您无忧上云