在向表单MVC中插入数据后,在视图中显示错误或成功消息
本文关键字:错误 显示 消息 成功 视图 表单 MVC 插入 数据 | 更新日期: 2023-09-27 18:18:17
我需要在视图中填充表单后显示错误或成功消息,如果控制器的action方法捕获异常,则显示表单注册成功与否的消息。
这是我的HTML代码的形式:@using (Html.BeginForm("GetSolictudMarca", "Gestion", FormMethod.Post, new { @id = "Frm-login", role = "form", @class = "form-horizontal" }))
{
<div class="panel panel-default" style="width:80%;margin:0 auto;">
<div class="panel-heading"></div>
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<br />
<div class="form-group-sm">
<div class="col-lg-10">
<p> <strong>Nº Expediente:</strong></p>
<input class="form-control" id="expedienteNro" name="expedienteNro" type="number" placeholder="Nº Expediente" required autocomplete="off" onkeypress="return pulsarExpediente(event)">
</div>
</div>
</div>
</div>
<br />
<div class="row ">
<div class="col-lg-6">
<div class="form-group-sm">
<div class="col-lg-10">
<p><strong>Fecha Solicitud:</strong></p>
@(Html.Kendo().DateTimePicker()
.Name("fechaSolicitud")
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width:100%;", required = "required" })
)
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group-sm">
<div class="col-lg-10">
<p><strong>Fecha Estado:</strong></p>
@(Html.Kendo().DateTimePicker()
.Name("fechaEstado")
.Value(DateTime.Now)
.HtmlAttributes(new { style = "width:100%;", required = "required" })
)
</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-lg-6">
<div class="form-group-sm">
<div class="col-lg-10">
<p><strong>Pais:</strong></p>
@(Html.Kendo().ComboBox()
.Name("pais2")
.DataTextField("PaisDescripcion")
.DataValueField("PaisCodigo")
.HtmlAttributes(new { style = "width:100%", required = "required" })
.Filter(FilterType.StartsWith)
.IgnoreCase(true)
.Placeholder("Seleccione un país...")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetPais", "Gestion");
});
})
)
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4" style="margin-left:30px; margin-top:30px; width:100%">
<button class="btn btn-success" type="submit" id="btnRegistrar">Registrar</button>
<button class="btn btn-success" type="reset">Cancelar</button>
</div>
</div>
<div class="row">
@*@Html.ValidationSummary("error")*@
<div class="alert ">
@Html.ValidationMessage("error", new { @id = "validationMessage" })
</div>
</div>
</div>
</div>
}
我的控制器:
public async Task<ActionResult> GetSolictudMarca(FormCollection frm)
{
string ExpedienteGeneral = Request.Form["expedienteNro"];
string fechaSolicitud = Request.Form["fechaSolicitud"];
string fechaEstado = Request.Form["fechaEstado"];
string pais = Request.Form["pais2"];
return await Task.Run(() =>
{
string sqlString = "select * from gmc_expediente where exp_codigo = :selectExpNro";
string queryRoles = "insert into gmc_expediente(EXP_CODIGO,'n" +
"EXP_FECHA_SOLICITUD,'n" +
"EXP_FECHA_ESTADO,'n" +
"EXP_PAIS)'n" +
"values(:ExpCodigo,'n" +
" :fechaSolicitud ,'n" +
" :fechaEstado,'n" +
" :pais)";
#region Conexion
string cadena = ConfigurationManager.ConnectionStrings["OracleDbContext"].ConnectionString;
OracleConnection con = new OracleConnection(cadena);
OracleCommand cmd = new OracleCommand(queryRoles, con);
cmd.Parameters.Add(new OracleParameter("ExpCodigo", string.IsNullOrEmpty(nuevoExpediente) ? int.Parse(ExpedienteGeneral) : int.Parse(nuevoExpediente)));
cmd.Parameters.Add(new OracleParameter("fechaSolicitud", DateTime.Parse(fechaSolicitud)));
cmd.Parameters.Add(new OracleParameter("fechaEstado", DateTime.Parse(fechaEstado)));
cmd.Parameters.Add(new OracleParameter("pais", int.Parse(pais)));
#region Procedimiento
try
{
con.Open();
Permisos.OtorgarPermisos(con);
using (OracleDataReader dr = cmd2.ExecuteReader())
{
while (dr.Read())
{
//make an insert or update into database
}
}
}
catch (Exception ex)
{
//and here when i catch the exception show the message in the view
}
finally
{
if (con.State == System.Data.ConnectionState.Open)
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
#endregion
return RedirectToAction("RegistroMarca");
});
}
所有我需要的是,如果控制器的方法动作捕捉到一个异常,显示异常的确切类型到消息和显示到视图中。如果可能的话,像这样的bootstrap警告消息:
<div class="alert alert-success" id="mostrarAlertSuccess" style="display:none; margin-top:10px">
<strong>¡Eliminación exitosa!</strong> El registro fue eliminado correctamente.
</div>
<div class="alert alert-danger" id="mostrarAlertDanger" style="display:none; margin-top:10px">
<strong>Danger!</strong> Indicates a dangerous or potentially negative action.
</div>
我会用TempData["key"]
这与ViewData["key"]
类似,但是数据会保留到下一个HttpRequest,并在此
[HttpPost]
public ActionResult SomePostAction(SomeViewModel vm)
{
if(ModelState.IsValid) // Is User Input Valid?
{
try
{
CommitData();
TempData["UserMessage"] = new { CssClassName = "alert-sucess", Title = "Success!", Message = "Operation Done." };
return RedirectToAction("Success");
}
catch(Exception e)
{
TempData["UserMessage"] = new { CssClassName = "alert-error", Title = "Error!", Message = "Operation Failed." };
return RedirectToAction("Error");
}
}
return View(vm); // Return View Model with model state errors
}
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
</head>
<body>
@if(TempData["UserMessage"] != null)
{
<div class="alert @TempData["UserMessage"].CssClassName">
<strong>@TempData["UserMessage"].Title</strong> @TempData["UserMessage"].Message
</div>
}
@RenderBody()
</body>
</html>