我想使用viewmodel编写编辑代码,但我完全不解。
这是我的viewmodel
public SearchCustomersCriteria SearchCustomersCriteria { get; set; }
public SearchCustomersResults SearchCustomersResults { get; set; }
public SearchProductsCriteria SearchProductsCriteria { get; set; }
public SearchProductsResults SearchProductsResults { get; set; }
public List<SelectedProduct> ListOfSelectedProducts { get; set; }
public int OrderId { get; set; }
public decimal Deposit { get; set; }
public DateTime DeliveryDate { get; set; }
//public string Status { get; set; }
public System.DateTime CreatedOn { get; set; }
//public SelectedProduct SelectedProduct { get; set; }
public BentleyBeds.InternalManagement.Web.Utility.Helper.OrderStatus Status { get; set; }
}
#endregion
#region Selected products
public class SelectedProduct
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
public bool Deleted { get; set; }
}
#endregion
#region Customer search
public class SearchCustomersCriteria
{
public string FristName { get; set; }
public string LastName { get; set; }
}
public class SearchCustomersResults
{
public List<Data.Customer> ListOfCustomers { get; set; }
public int SelectedCustomerId { get; set; }
}
#endregion
#region Products
public class SearchProductsCriteria
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class SearchProductsResults
{
public List<Data.Product> ListOfProducts { get; set; }
public int SelectedProductId { get; set; }
}
}
这是控制器
public ActionResult Create()
{
var model = new CreateOrderViewModel();
//model.ListOfSelectedProducts = new List<SelectedProduct>(){
// new SelectedProduct(){Description="ab", ProductName ="abc", Quantity=0, UnitPrice=0}};
model.ListOfSelectedProducts = new List<SelectedProduct>();
model.SearchCustomersCriteria = new SearchCustomersCriteria();
model.SearchCustomersResults = new SearchCustomersResults();
model.SearchProductsCriteria = new SearchProductsCriteria();
model.SearchProductsResults = new SearchProductsResults();
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateOrderViewModel model, List<string> ProductName, List<SetupProductViewModel> productViewModel, string FristName)
{
//if (ModelState.IsValid)
//{
try
{
var status = model.Status.ToString();
var deliver = model.DeliveryDate;
using (var ctx = new BentleyBedsEntities())
{
//add into orders
var order = new Order()
{
CustomerId = model.SearchCustomersResults.SelectedCustomerId,
DeliveryDate = model.DeliveryDate,
Deposit = model.Deposit,
StatusId = helper.GetEnumKey(status),
CreatedOn = DateTime.Now
};
ctx.Orders.Add(order);
//var result = ctx.SaveChanges();
var id = order.OrderId;
if (ctx.Orders.Any(e => e.OrderId == id))
{
ctx.Orders.Attach(order);
//tx.ObjectStateManager.ChangeObjectState(myEntity, EntityState.Modified);
}
else
{
ctx.Orders.Add(order);
}
var result = ctx.SaveChanges();
if (result > 0)
{
var orderId = order.OrderId;
foreach (SelectedProduct selectedProduct in model.ListOfSelectedProducts)
{
if (!selectedProduct.Deleted)
{
var orderDetails = new OrdersDetail()
{
OrderId = orderId,
ProductId = selectedProduct.ProductId,
Price = selectedProduct.UnitPrice,
Quantity = selectedProduct.Quantity,
Description = selectedProduct.Description
};
ctx.OrdersDetails.Add(orderDetails);
var results = ctx.SaveChanges();
}
}
}
}
}
catch (DbUpdateException ex)
{
UpdateException updateException = (UpdateException)ex.InnerException;
SqlException sqlException = (SqlException)updateException.InnerException;
foreach (SqlError error in sqlException.Errors)
{
// TODO: Do something with your errors
var result = error.Message;
}
}
catch (Exception ex)
{
var stat = ex.ToString();
return View("Create", model);
//throw;
}
return RedirectToAction("Index");
//}
//return View("Create", model);
}
// GET: /CreateOrder/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = context.Orders.Find(id);
if (order == null)
{
return HttpNotFound();
}
ViewBag.CustomerId = new SelectList(context.Customers, "Firstname", "Firstname", order.Customer.Firstname);
return View(order);
}
// POST: /CreateOrder/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "OrderId,CustomerId,Customer,Firstname,Deposit,DeliveryDate,StatusId,CreatedBy,CreatedOn,CompanyID")] Order order)
{
if (ModelState.IsValid)
{
context.Entry(order).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CustomerId = new SelectList(context.Customers, "Firstname", "Firstname", order.Customer.Firstname);
return View(order);
}
我应该如何在控制器和视图中编写编辑代码?
答案 0 :(得分:0)
以下是如何使用ViewModel创建编辑代码的示例。首先,根据要编辑的模型中的特定项创建ViewModel的类。
例如,我们假设您有一个Book类:
public class Book
{
public int BookID { get; set; }
public string Name { get; set; }
public int LibraryID { get; set; }
}
现在,您希望ViewModel仅编辑图书的名称。然后,它看起来像这样:
public class EditBookViewModel
{
public int BookID { get; set; }
[Required]
public string Name { get; set; }
}
在您的控制器中,您将获得一种方法&#39;获取&#39;返回数据,并发布&#39; Post&#39;将数据放回数据库的方法。它看起来像这样:
public class YourController
{
...
public ActionResult Edit(int id)
{
Book book = ctx.Books.Find(id);
var viewModel = new EditBookViewModel()
{
BookID = book.BookID,
Name = book.Name
}
return View(viewModel);
}
[HttpPost]
public ActionResult Edit(EditBookViewModel viewModel)
{
if (ModelState.IsValid)
{
var model = ctx.Books.Find(model.BookID);
viewModel.Name = model.Name;
ctx.SaveChanges();
}
return RedirectToAction("Index");
}
...
}
确保您的视图已准备好接收EditBookViewModel。您可以通过在视图顶部添加来执行此操作:
@model EditBookViewModel