[英]How to determine which view to redirect to using ViewModels?
I am currently using ViewModels to bind to all my CRUD operations, but there are some action methods only returning partial views: 我目前正在使用ViewModels绑定到我的所有CRUD操作,但有一些操作方法只返回部分视图:
public ActionResult Create(int parentId)
{
var viewModel = new MyCreateViewModel();
return PartialView("_Create", viewModel);
}
These actions will be called from different views (different entities) via AJAX, and displayed in a jQuery dialog. 这些操作将通过AJAX从不同的视图(不同的实体)调用,并显示在jQuery对话框中。 The dialog buttons will handle the POST
ing of the form via $("#form").submit()
, and another action method will process the form, ideally redirecting to the parent view that called the partial view : 对话框按钮将通过$("#form").submit()
处理表单的POST
,另一个操作方法将处理表单, 理想情况下重定向到调用局部视图的父视图 :
[HttpPost]
public ActionResult Create(int parentId, MyCreateViewModel viewModel)
{
//Process the viewModel, map to EF models and persist to the database
return RedirectToAction(/*What should I insert here?*/);
}
Since I do not know which view is POST
ing to this method, how can I know which view should I redirect to? 由于我不知道哪个视图是POST
到此方法,我怎么知道我应该重定向到哪个视图?
I would add a string property to your viewModel that contains the name of the view you want to return 我会在viewModel中添加一个字符串属性,其中包含要返回的视图的名称
[HttpPost]
public ActionResult Create(int parentId, MyCreateViewModel viewModel)
{
//Process the viewModel, map to EF models and persist to the database
return RedirectToAction(viewModel.ViewToRender);
}
You can redirect in client side instead of doing that in the action method. 您可以在客户端重定向,而不是在操作方法中执行此操作。 In the action method, you can return a result indicating the operation is success or fail. 在action方法中,您可以返回指示操作成功或失败的结果。 In the client side, use $.ajax to handle the result 在客户端,使用$ .ajax来处理结果
$('#form').submit(function () {
var self = $(this);
if (self.valid()) {
$.ajax({
type: "POST",
url: self.attr('action'),
data: self.serialize(),
success: function (data) {
if (data.Success == true) {
//redirect
} else{
//Error handling
}
},
error: function (ex) {
//Error handling
}
});
}
return false;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.