ViewBag到达空

时间:2019-07-16 19:08:23

标签: c# asp.net-mvc

我有一个在数据库中注册聊天的表格,一切正常,问题在于ViewBag,因为它将消息传递到视图中的Javascript以便进行验证。当用户注册时,应该显示一条成功消息,但是如果显示了用户数据,则ViewBag会在数据库中将其显示为错误,因此唯一的问题就是ViewBag。

此外,当我再次运行时,显示成功消息的模式也很好。

控制器

//Charlas
    public ActionResult CrearCharla()
    {
        List<ClsSede> listaSede = new List<ClsSede>();

        ClsSede Sede1 = new ClsSede();
        Sede1.sede_Text = "LIMA - SAN BORJA";
        Sede1.sede_Value = "LIMA - SAN BORJA";

        ClsSede Sede2 = new ClsSede();
        Sede2.sede_Text = "LIMA - LOS OLIVOS";
        Sede2.sede_Value = "LIMA - LOS OLIVOS";

        ClsSede Sede3 = new ClsSede();
        Sede3.sede_Text = "LIMA - CHORRILLOS";
        Sede3.sede_Value = "LIMA - CHORRILLOS";

        listaSede.Add(Sede1);
        listaSede.Add(Sede2);
        listaSede.Add(Sede3);

        ViewBag.Sedes = new SelectList(listaSede, "sede_Text", "sede_Value");

        return View(new ClsCharla());
    }

    [HttpPost]
    public ActionResult CrearCharla(ClsCharla charla)
    {

        List<ClsSede> listaSede = new List<ClsSede>();

        ClsSede Sede1 = new ClsSede();
        Sede1.sede_Text = "LIMA - SAN BORJA";
        Sede1.sede_Value = "LIMA - SAN BORJA";

        ClsSede Sede2 = new ClsSede();
        Sede2.sede_Text = "LIMA - LOS OLIVOS";
        Sede2.sede_Value = "LIMA - LOS OLIVOS";

        ClsSede Sede3 = new ClsSede();
        Sede3.sede_Text = "LIMA - CHORRILLOS";
        Sede3.sede_Value = "LIMA - CHORRILLOS";

        listaSede.Add(Sede1);
        listaSede.Add(Sede2);
        listaSede.Add(Sede3);

        ViewBag.Sedes = new SelectList(listaSede, "sede_Text", "sede_Value", charla.sede_Charla);

        //-----

        string message = "";

        try
        {
            ClsConexion con = new ClsConexion();
            var Cnx = con.Conexion();

            OracleCommand cmd = new OracleCommand("SIMEXA_SP_REGISTER_CHAT", Cnx);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new OracleParameter("param_titulo", OracleDbType.Varchar2)).Value = charla.titulo_Charla.Trim();
            cmd.Parameters.Add(new OracleParameter("param_descrip", OracleDbType.Varchar2)).Value = charla.descrip_Charla.Trim();
            cmd.Parameters.Add(new OracleParameter("param_fecha", OracleDbType.Varchar2)).Value = charla.fecha_Charla;
            cmd.Parameters.Add(new OracleParameter("param_hora", OracleDbType.Varchar2)).Value = charla.hora_Charla;
            cmd.Parameters.Add(new OracleParameter("param_lugar", OracleDbType.Varchar2)).Value = charla.lugar_Charla.Trim();
            cmd.Parameters.Add(new OracleParameter("param_sede", OracleDbType.Varchar2)).Value = charla.sede_Charla;
            cmd.Parameters.Add(new OracleParameter("param_requisito", OracleDbType.Varchar2)).Value = charla.requisito_Charla.Trim();
            Cnx.Open();

            OracleTransaction tx = Cnx.BeginTransaction();
            cmd.ExecuteNonQuery();
            tx.Commit();

            Cnx.Close();
            cmd.Dispose();
            Cnx.Dispose();

            message = "success";

        }
        catch
        {
            message = "error";
        }
        finally
        {
            ViewBag.message = message;
        }

        return RedirectToAction("MostraCharlas");

    }

查看

    @model wsCharlas.Models.ClsCharla

@{
    ViewBag.Title = "Create a Chat";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create a Chat:</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <h4>Here you can place all the respective data of the chat you want to create.</h4>
    <hr />

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <!--    <div class="form-horizontal"> -->
    <div class="form-group">
        @Html.HiddenFor(model => model.ID_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.HiddenFor(model => model.ID_Charla, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ID_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.titulo_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.EditorFor(model => model.titulo_Charla, new { htmlAttributes = new { @class = "form-control", maxlength = "40" } })
            @Html.ValidationMessageFor(model => model.titulo_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.descrip_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.TextAreaFor(model => model.descrip_Charla, new { @id = "textArea", @class = "form-control", maxlength = "530" })
            @Html.ValidationMessageFor(model => model.descrip_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.fecha_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.EditorFor(model => model.fecha_Charla, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.fecha_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.hora_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.EditorFor(model => model.hora_Charla, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.hora_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.lugar_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.EditorFor(model => model.lugar_Charla, new { htmlAttributes = new { @class = "form-control", maxlength = "100" } })
            @Html.ValidationMessageFor(model => model.lugar_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.sede_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.DropDownListFor(model => model.sede_Charla, (SelectList)ViewBag.Sedes, "Select a Headquarters", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.sede_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.requisito_Charla, htmlAttributes: new { @class = "control-label" })
        <div>
            @Html.EditorFor(model => model.requisito_Charla, new { htmlAttributes = new { @class = "form-control", maxlength = "100" } })
            @Html.ValidationMessageFor(model => model.requisito_Charla, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2">
            <input type="submit" value="Create a Chat" id="id_charla"  class="btn btn-success" />
        </div>
    </div>
    <!--</div> -->
}

<div>
    @Html.ActionLink("Return", "MostraCharlas", null, new { @class = "btn btn-primary" })
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

<style>
    #textArea{
        min-height: 62px;
        max-height: 135px;
    }
</style>

<script>

    var msg = '@ViewBag.message'

    $("#id_charla").on("click", function () {
        if (msg == 'success') {
            Swal.fire(
                        msg,
                        'A new chat was added!',
                        'success'
                     )
        } else {
            Swal.fire(
                        msg,
                        'Could not register your new chat, be sure to complete the entire form, if the problem continues to communicate with the computer area!',
                        'error'
                     )
        }   
    });

</script>

1 个答案:

答案 0 :(得分:3)

为回答您的问题,我首先要说的是,ViewBag的空值是正确的,因为您使用了RedirectToAction

ViewBag的生存期是当前请求,这意味着一旦您尝试离开当前请求,该请求就为空。因此,您需要针对自己的情况使用TempData

TempData是一种数据,仅用于存储会话。这是两个请求之间的最后一生。它有助于将数据从一个控制器传输到另一个或从一个动作传输到另一个。您使用临时数据的方式与使用查看数据的方式略有不同。

所以我将为您提供两个选择。

第一

使用TempData和ViewBag

在“发布”操作中,将最后一行更改为

finally
{
    TempData["message"] = message;
}

然后在您要重定向到的Get操作中,因为您使用RedirectToAction获取了TempData并将其传递给view bag

var message = TempData ["message"];
If(message != null)
    ViewBag.message = message;

注意 需要if语句来处理初始获取请求,即在未设置TempData时不设置ViewBag的值

第二

仅使用TempData

finally
{
    TempData["message"] = message;
}

无论您决定使用哪种方式,都可以通过分配方式访问

TempData["message"] //for TempData
ViewBag.message //for ViewBag