c# - 如何将数据从视图模型传递到?
问题描述
我是 MVC 的新手,并试图了解视图模型。我有Staff
, Service
, BookingSlot
,Appointments
和ApplicationUser
实体。我有以下视图模型:
public class AppointmentBookingViewModel
{
[Display (Name ="Select Staff")]
public int StaffId { get; set; }
public IEnumerable<Staff> Staffs { get; set; }
[Display(Name = "Select Service")]
public int ServiceId { get; set; }
public IEnumerable<Service> Services { get; set; }
[Display(Name = "Select Slot")]
public int BookingSlotId { get; set; }
public IEnumerable<BookingSlot> BookingSlots { get; set; }
}
这是控制器:
public class AppointmentBookingController : Controller
{
private readonly SalonContext _context;
private AppointmentBookingViewModel _appointmentBookingViewModel = new AppointmentBookingViewModel();
public AppointmentBookingController(SalonContext context)
{
_context = context;
ConfigureViewModel(_appointmentBookingViewModel);
}
public void ConfigureViewModel(AppointmentBookingViewModel appointmentBookingViewModel)
{
appointmentBookingViewModel.Staffs = _context.Staffs;
appointmentBookingViewModel.Services = _context.Services;
appointmentBookingViewModel.BookingSlots = _context.BookingSlots;
}
// GET: AppointmentBooking
public ActionResult Index()
{
return View(_appointmentBookingViewModel);
}
}
我的问题是,如何在视图中创建表单并将数据发布到约会表,以下不起作用。
@model HairStudio.Services.ViewModels.AppointmentBooking.AppointmentBookingViewModel
@{
ViewData["Title"] = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="col-12">
<form asp-action="Create">
<div class="form-group">
<label asp-for="ServiceId" class="control-label"></label>
<select asp-for="ServiceId" class="form-control"></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
解决方案
您已经将表单定向到带有属性的名为“创建”的操作,但您的控制器asp-action
中没有这样的操作。提交表单会发送一个 HTTP POST 请求,该请求需要由您的控制器处理。因此,在你的添加一个方法:Create()
AppointmentBookingController
// POST: Create
public IActionResult Create(AppointmentBookingViewModel appointmentViewModel)
{
if (!ModelState.IsValid)
{
// Server side validation of form has failed.
// Return to the calling view and inform the user about the errors.
return View(appointmentViewModel, "Index");
}
return View(appointmentViewModel, "<NAME_OF_YOUR_CREATED_APPOINTMENT_VIEW>");
}
考虑根据设计模式Post/Redirect/Get在成功接受 HTTP POST 请求后进行重定向。
此外,请查看有关使用表单的 ASP.NET Core 文档的这一部分。我相信你会在那里找到一些有价值的东西。
推荐阅读
- ansible - 我怎样才能把它变成一个 Ansible 剧本?
- sql - SQL Server 用不同表的列映射行
- c# - TwilioRequestValidator 中的瞬态 System.Security.Cryptography.CryptographicException
- java - 为什么 Math#nextUp 不增加 Double.MIN_VALUE?
- c++ - 使用 GCC 编译的多线程 MKL + OpenMP
- java - Is it possible to retrieve the attributes of an Object I saved inside a .dat file in Java?
- javascript - JavaScript 为相同的参数值返回不同的输出
- ruby - 升级 Cucumber 2.4 -> 4.0 失败:无法加载此类文件 -- cucumber/core/gherkin/tag_expression (LoadError)
- typescript - TypeScript 中有没有一种方法可以在不丢失对象特异性的情况下使用接口作为保护?
- c++ - 如何从精明的图像中去除高频区域?