返回部分视图和消息
Returning both Partial View and a Message
我有一个可以更改连接字符串的局部视图。提交时调用 Edit
操作。如果我想让用户再试一次,我想从这里 return 重新打开局部视图。如果一切顺利(或崩溃),我想调用我的 JavaScript 函数 Logout
,将用户注销并重定向到某个起始页。
两种解决方案都有效,只是不能同时使用。我显然缺少一些最佳实践,我该怎么办?
部分视图:EditSetting
@model WebConsole.ViewModels.Setting.SettingViewModel
@using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }, new { id = "editform" }))
{
<fieldset>
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
@Html.LabelFor(model => model.User, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.User, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.User, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
<input type="password" name="Password" id="Password" value=""/>
@Html.ValidationMessageFor(model => model.Password, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DataSource, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.DataSource, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.DataSource, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.InitialCatalog, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.InitialCatalog, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.InitialCatalog, "", new {@class = "text-danger"})
</div>
</div>
</div>
</fieldset>
}
JavaScript: 提交
$('form').submit(function () {
var $self = $(this);
if ($(this).valid()) {
// Change Connection String
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (message) {
// Use Partial View
//$('#myModal .modal-body').html(message);
// Conn Str is now changed. Log out and redirect
logOut($self, message);
},
error: function (message) {
logOut($self, message);
}
});
}
return false;
});
操作:编辑
[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
// Validate inputs
if (!ModelState.IsValid)
{
ModelState.AddModelError("", @"Not all inputs are valid.");
return PartialView("EditSetting", model);
}
var sql = new DAL.SQL(DAL.SQL.GenerateConnectionString(model.DataSource, model.InitialCatalog, model.User, SecurePassword(model.Password)));
// Validate Connection String
if (!sql.Open())
{
ModelState.AddModelError("", @"Error. Unable to open connection to Database.");
return PartialView("EditSetting", model);
}
// Validate a transaction
if (!sql.IsRunningTransact())
{
ModelState.AddModelError("", @"Error. Unable to connect to Database Server.");
return PartialView("EditSetting", model);
}
// Save Connection String
BuildAndEncryptConnString(model);
return Content("The Connection String is changed. Log in again to continue.");
}
您可以Return Patial View,并初始化ViewBag 并将消息分配给它,然后在视图中检查是否有值,如果为真则显示它。
控制器:
[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
// Put the ViewBag where ever you want
ViewBag.ErrorMsg =" Error";
return PartialView("EditSetting", model);
}
查看:
@if(ViewBag.ErrorMsg !=null )
{
<div>@ViewBag.ErrorMsg</div>
}
希望对您有所帮助。
使用扩展方法 RenderToString and basead on cacois answer,您可以像这样创建您的操作:
public ActionResult Edit(SettingViewModel model)
{
// "Ifs" to return only partials
if (ModelState.IsValid)
{
return PartialView("EditSetting", model);
}
...
// Returning a Json with status (success, error, etc), message, and the content of
// your ajax, in your case will be a PartialView in string
return Json(new {
Status = 1,
Message = "error message",
AjaxReturn = PartialView("EditSetting", model).RenderToString()});
}
Ps。我建议您创建一个模型来定义 Ajax return,其中 Status
、Message
和 AjaxReturn
。这样一来,您的 ajax 请求将始终 return 相同的对象类型。对于 Status
属性 你可以创建一个枚举。
您的 ajax 请求将是这样的:
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
if(data.Message == undefined) {
// Use data like a partial
} else {
// Use data.Message for the message and data.AjaxReturn for the partial
}
},
error: function (message) {
logOut($self, message);
}
});
向您的 ViewModel 添加错误处理:
bool hasErrors;
string errorMessage;
在您的控制器中,如果数据验证正常,只需 return PartialView 或 return RedirectToAction("Index");
。如果不是,请设置 hasErros = true;
和自定义 errorMessage
.
在视图中,将错误块 someone 放置在用户将看到的位置:
@if (Model.hasErrors)
{
<div>Model.errorMessage</div>
}
顺便说一句,您可以在 ViewModel 构造函数中进行数据验证。
我有一个可以更改连接字符串的局部视图。提交时调用 Edit
操作。如果我想让用户再试一次,我想从这里 return 重新打开局部视图。如果一切顺利(或崩溃),我想调用我的 JavaScript 函数 Logout
,将用户注销并重定向到某个起始页。
两种解决方案都有效,只是不能同时使用。我显然缺少一些最佳实践,我该怎么办?
部分视图:EditSetting
@model WebConsole.ViewModels.Setting.SettingViewModel
@using (Ajax.BeginForm("Edit", "Setting", new AjaxOptions { UpdateTargetId = "div" }, new { id = "editform" }))
{
<fieldset>
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
@Html.LabelFor(model => model.User, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.User, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.User, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Password, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
<input type="password" name="Password" id="Password" value=""/>
@Html.ValidationMessageFor(model => model.Password, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DataSource, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.DataSource, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.DataSource, "", new {@class = "text-danger"})
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.InitialCatalog, htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-10">
@Html.EditorFor(model => model.InitialCatalog, new {htmlAttributes = new {@class = "form-control"}})
@Html.ValidationMessageFor(model => model.InitialCatalog, "", new {@class = "text-danger"})
</div>
</div>
</div>
</fieldset>
}
JavaScript: 提交
$('form').submit(function () {
var $self = $(this);
if ($(this).valid()) {
// Change Connection String
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (message) {
// Use Partial View
//$('#myModal .modal-body').html(message);
// Conn Str is now changed. Log out and redirect
logOut($self, message);
},
error: function (message) {
logOut($self, message);
}
});
}
return false;
});
操作:编辑
[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
// Validate inputs
if (!ModelState.IsValid)
{
ModelState.AddModelError("", @"Not all inputs are valid.");
return PartialView("EditSetting", model);
}
var sql = new DAL.SQL(DAL.SQL.GenerateConnectionString(model.DataSource, model.InitialCatalog, model.User, SecurePassword(model.Password)));
// Validate Connection String
if (!sql.Open())
{
ModelState.AddModelError("", @"Error. Unable to open connection to Database.");
return PartialView("EditSetting", model);
}
// Validate a transaction
if (!sql.IsRunningTransact())
{
ModelState.AddModelError("", @"Error. Unable to connect to Database Server.");
return PartialView("EditSetting", model);
}
// Save Connection String
BuildAndEncryptConnString(model);
return Content("The Connection String is changed. Log in again to continue.");
}
您可以Return Patial View,并初始化ViewBag 并将消息分配给它,然后在视图中检查是否有值,如果为真则显示它。
控制器:
[HttpPost]
public ActionResult Edit(SettingViewModel model)
{
// Put the ViewBag where ever you want
ViewBag.ErrorMsg =" Error";
return PartialView("EditSetting", model);
}
查看:
@if(ViewBag.ErrorMsg !=null )
{
<div>@ViewBag.ErrorMsg</div>
}
希望对您有所帮助。
使用扩展方法 RenderToString and basead on cacois answer,您可以像这样创建您的操作:
public ActionResult Edit(SettingViewModel model)
{
// "Ifs" to return only partials
if (ModelState.IsValid)
{
return PartialView("EditSetting", model);
}
...
// Returning a Json with status (success, error, etc), message, and the content of
// your ajax, in your case will be a PartialView in string
return Json(new {
Status = 1,
Message = "error message",
AjaxReturn = PartialView("EditSetting", model).RenderToString()});
}
Ps。我建议您创建一个模型来定义 Ajax return,其中 Status
、Message
和 AjaxReturn
。这样一来,您的 ajax 请求将始终 return 相同的对象类型。对于 Status
属性 你可以创建一个枚举。
您的 ajax 请求将是这样的:
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
if(data.Message == undefined) {
// Use data like a partial
} else {
// Use data.Message for the message and data.AjaxReturn for the partial
}
},
error: function (message) {
logOut($self, message);
}
});
向您的 ViewModel 添加错误处理:
bool hasErrors;
string errorMessage;
在您的控制器中,如果数据验证正常,只需 return PartialView 或 return RedirectToAction("Index");
。如果不是,请设置 hasErros = true;
和自定义 errorMessage
.
在视图中,将错误块 someone 放置在用户将看到的位置:
@if (Model.hasErrors)
{
<div>Model.errorMessage</div>
}
顺便说一句,您可以在 ViewModel 构造函数中进行数据验证。