如何在MVC中使用ViewModel进行编辑? [英] How to Edit using a ViewModel in MVC?

查看:78
本文介绍了如何在MVC中使用ViewModel进行编辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MVC的新手,正在尝试了解ViewModels.我了解如何使用Create和ViewModel,但是不确定如何使用View Model进行编辑吗?

I am new to MVC and trying to understand ViewModels. I understand how to use Create and a ViewModel, But am unsure how to Edit using a View Model?

我的VM:

public class BookingViewModel
{
    [Display (Name = "Select Patient")]
    public Guid PatientId { get; set; }
    public IEnumerable<SelectListItem> PatientList { get; set; }

    [Display(Name = "Select Practice")]
    public Guid PracticeId { get; set; }
    public IEnumerable<SelectListItem> PracticeList { get; set; }

    [Display(Name = "Select Optician")]
    public Guid OpticianId { get; set; }
    public IEnumerable<SelectListItem> OpticiansList { get; set; }

    public Optician Optician { get; set; }

    [Display(Name = "Select Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime Date { get; set; }

    [Display(Name = "Select Time")]
    public Guid TimeId { get; set; }
    public IEnumerable<SelectListItem> TimeList { get; set; }
}

我的控制器:

public ActionResult Create()
{
    // Creates a new booking
    BookingViewModel bookingViewModel = new BookingViewModel();
    // Initilises Select List
    ConfigureCreateViewModel(bookingViewModel);

    return View(bookingViewModel);

}

// Initilises Select List 
public void ConfigureCreateViewModel(BookingViewModel bookingViewModel)
{
    // Displays Opticians Name - Needs changed to full name
    bookingViewModel.OpticiansList = db.Opticians.Select(o => new SelectListItem()
    {
        Value = o.OpticianId.ToString(),
        Text = o.User.FirstName
    });

    // Displays Patients name - needs changed to full name DOB
    bookingViewModel.PatientList = db.Patients.Select(p => new SelectListItem()
    {
        Value = p.PatientId.ToString(),
        Text = p.User.FirstName
    });

    // Displays Practice Name
    bookingViewModel.PracticeList = db.Practices.Select(p => new SelectListItem()
    {
        Value = p.PracticeId.ToString(),
        Text = p.PracticeName
    });

    // Displays Appointment Times 
    bookingViewModel.TimeList = db.Times.Select(t => new SelectListItem()
    {
        Value = t.TimeId.ToString(),
        Text = t.AppointmentTime
    });


}


// Allows Admin to create booking for patient 
// POST: Bookings1/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(BookingViewModel bookingViewModel)
{
    // to ensure date is in the future
    if (ModelState.IsValidField("Date") && DateTime.Now > bookingViewModel.Date)
    {
        ModelState.AddModelError("Date", "Please enter a date in the future");
    }



    // if model state is not valid
    if (!ModelState.IsValid)
    {
        // Initilises Select lists
        ConfigureCreateViewModel(bookingViewModel);
        return View(bookingViewModel); // returns user to booking page
    }
    else // if model state is Valid
    {
        Booking booking = new Booking();
        // Sets isAvail to false
        booking.isAvail = false;
        booking.PracticeId = bookingViewModel.PracticeId;
        booking.Optician = bookingViewModel.Optician;
        booking.PatientId = bookingViewModel.PatientId;
        booking.Date = bookingViewModel.Date;
        booking.TimeId = bookingViewModel.TimeId;

        // Generates a new booking Id
        booking.BookingId = Guid.NewGuid();
        // Adds booking to database
        db.Bookings.Add(booking);
        // Saves changes to Database
        db.SaveChanges();
        // Redirects User to Booking Index
        return RedirectToAction("Index");
    }
}

我真的不确定如何编辑视图模型,任何建议将不胜感激

I am really unsure how to Edit a View Model, any advice would be greatly appreciated

public ActionResult Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Booking booking = db.Bookings.Find(id);
    if (booking == null)
    {
        return HttpNotFound();
    }

    BookingViewModel bookingViewModel = new BookingViewModel()
    {
        Date = booking.Date,
        OpticianId = booking.OpticianId,
        PatientId = booking.PatientId,
        PracticeId = booking.PracticeId,
        TimeId = booking.TimeId
    };

    return View(booking, bookingViewModel);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Booking booking)
{


    if (ModelState.IsValid)
    {

        db.Entry(booking).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(booking);
}

推荐答案

Edit() GET方法必须是

public ActionResult Edit(Guid? id)
{
  ....
  BookingViewModel bookingViewModel = new BookingViewModel()
  {
    ....
  }
  // Call the ConfigureCreateViewModel() method so that you SelectList's are populated 
  // as you have done in the Create() method (ConfigureViewModel might be a better name?)
  ConfigureCreateViewModel(bookingViewModel);
  return View(bookingViewModel); // adjust this
}

并且POST方法必须为

and the POST method needs to be

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(BookingViewModel model)
{
  if (!ModelState.IsValid)
  {
    ConfigureCreateViewModel(model)
    return View(model);
  }
  // Get your data model and update its properties based on the view model
  Booking booking = db.Bookings.Find(id);
  booking.PracticeId = bookingViewModel.PracticeId;
  booking.OpticianId = bookingViewModel.OpticianId;
  .... // etc

  db.Entry(booking).State = EntityState.Modified;
  db.SaveChanges();
  return RedirectToAction("Index");
}

,并且您的视图应具有@model BookingViewModel

and your view should have @model BookingViewModel

旁注:您的视图模型应该包含属性public Optician Optician { get; set; }(您绑定到属性public Guid OpticianId { get; set; })

Side note: Your view model should not contain property public Optician Optician { get; set; } (you binding to the property public Guid OpticianId { get; set; })

这篇关于如何在MVC中使用ViewModel进行编辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆