首页 > 解决方案 > 如何将数据从视图模型传递到?

问题描述

我是 MVC 的新手,并试图了解视图模型。我有Staff, Service, BookingSlot,AppointmentsApplicationUser实体。我有以下视图模型:

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>

标签: c#asp.net-coreasp.net-core-mvc

解决方案


您已经将表单定向到带有属性的名为“创建”的操作,但您的控制器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 文档的这一部分。我相信你会在那里找到一些有价值的东西。


推荐阅读