是的,因为 Create 和 Edit 实际上是相同的,所以我通常会这样做:
控制器:
public class ActivityController : BaseController
{
public ActionResult Index()
{
var model = //Get your List model here...
return View(model);
}
public ActionResult Create()
{
var model = new ActivityModel(); //Create new instance of whatever your model is
return View("Edit", model); //NOTE: Pass the model to the "Edit view
}
public ActionResult Edit(int id)
{
var model = // your logic here to get your model based on ID param
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
try
{
// your logic here to delete based on ID param
return Json(new { Success = true, Message = "Entity updated" }); //AJAX result
}
catch (Exception x)
{
return Json(new { Success = false, Message = x.GetBaseException().Message }); //AJAX result
}
}
[HttpPost]
public ActionResult Update(ActivityModel model)//a single action to handle both add and edit operations
{
if (!ModelState.IsValid)
{
return Json(new { Success = false, Message = "Please correct any errors and try again" });//AJAX result
}
try
{
if (entity.Id == 0)
{
//your logic for inserting
}
else
{
//your logic for updating
}
return Json(new { Success = true });//AJAX result
}
catch (Exception x)
{
return Json(new { Success = false, Message = x.GetBaseException().Message }); //AJAX result
}
}
}
这样,我最常需要创建 2 个视图:Index.cshtml
和Edit.cshtml
.
只需记住在您的编辑视图中有这个:
@Html.HiddenFor(m => m.Id)
That will be used in the Update()
action to check whether you need to do an insert or update.
Without seeing your code, I'm not sure if that applies to your situation though...