【问题标题】:Can't get model attribute from razor ASP.net - C#无法从 razor ASP.net 获取模型属性 - C#
【发布时间】:2017-01-25 19:35:41
【问题描述】:

我有一个完全由模型完成的表单,但我无法获得某些属性,因为我相信此时模型为空。问题是,当我使用 @Model.someattribute 时它不起作用,但使用 m => m.cantidadMensajes 时,它会起作用。我需要知道它发生的原因以及我必须如何处理它?

@model SeaConnectionManager.Modelos.EnvioMensajes.InformacionEntity

@{ var previsualizaciones = "";
    if (@Model != null) { 
        previsualizaciones = @Model.vistaPrevia;
   }
}
<div id="Envio" class="overlay">
    <div class="popup">

        <h2 align="center">Información del Env&iacute;o</h2>
        <a class="close" href="#">&times;</a>
        <div class="content" style="width:100%; margin:auto; padding:10px">
            <center>
                <a id="tabs">
                    <ul>

                        @if (@Model != null) { 
                            if (@Model.cantidadMensajes >= 5)
                            {
                                for (var i = 1; i <= 5; i++)
                                {
                                    <li><a href="#tabs-@i"> @i</a></li>
                                }
                            }
                            else { 
                                for (var i = 1; i <= @Model.cantidadMensajes; i++)
                                {
                                    <li><a href="#tabs-@i"> @i</a></li>
                                }                
                            }
                        }

                    </ul>
                    @previsualizaciones
                </div>

                        <table width="100%" border="0" align="center" cellspacing="4">

                            <tr>
                                <td width="36%">Cantidad de mensajes</td>
                                <td width="44%">
                                    @Html.TextBoxFor(m => m.cantidadMensajes, new { @id = "CantidadMensajes", @class = "input-login", @readonly = "readonly" })
                                </td>
                            </tr>
                            <tr>
                                <td>Cantidad de contactos</td>
                                <td>
                                    @Html.TextBoxFor(m => m.cantidadContactos, new { @id = "CantidadContactos", @class = "input-login", @readonly = "readonly" })
                                </td>
                            </tr>
                            <tr>
                                <td>Saldo</td>
                                <td>
                                    @Html.TextBoxFor(m => m.saldo, new { @id = "Saldo", @class = "input-login", @readonly = "readonly" })
                                    @Html.HiddenFor(m => m.idTransaccion, new { @id = "idTransaccion" })
                                </td>
                            </tr>

                        </table>
            </center><br>
            <center>
                <table width="122" border="0" align="center" cellspacing="10">
                    <tr>
                        <td width="51"><a onclick="EnviarMensajes()" class="boton-para-enviar" style="margin:auto">Aprobar</a></td>
                        <td width="37"><a href="#" class="boton-para-NO-enviar" style="margin:auto">Rechazar</a></td>
                    </tr>
                </table>
            </center>

在没有运气的情况下遵循一些建议后的变化:

   @model SeaConnectionManager.Modelos.EnvioMensajes.InformacionEntity

@{ var previsualizaciones = "";
    if (Model != null) { 
        previsualizaciones = Model.vistaPrevia;
   }
}
<div id="Envio" class="overlay">
    <div class="popup">

        <h2 align="center">Información del Env&iacute;o</h2>
        <a class="close" href="#">&times;</a>
        <div class="content" style="width:100%; margin:auto; padding:10px">
            <center>
                <a id="tabs">
                    <ul>

                        @if (Model != null) { 
                            if (Model.cantidadMensajes >= 5)
                            {
                                for (var i = 1; i <= 5; i++)
                                {
                                    <li><a href="#tabs-@i"> @i</a></li>
                                }
                            }
                            else { 
                                for (var i = 1; i <= Model.cantidadMensajes; i++)
                                {
                                    <li><a href="#tabs-@i"> @i</a></li>
                                }                
                            }
                        }

                    </ul>
                    @previsualizaciones
                </div>

                        <table width="100%" border="0" align="center" cellspacing="4">

                            <tr>
                                <td width="36%">Cantidad de mensajes</td>
                                <td width="44%">
                                    @Html.TextBoxFor(m => m.cantidadMensajes, new { @id = "CantidadMensajes", @class = "input-login", @readonly = "readonly" })
                                </td>
                            </tr>
                            <tr>
                                <td>Cantidad de contactos</td>
                                <td>
                                    @Html.TextBoxFor(m => m.cantidadContactos, new { @id = "CantidadContactos", @class = "input-login", @readonly = "readonly" })
                                </td>
                            </tr>
                            <tr>
                                <td>Saldo</td>
                                <td>
                                    @Html.TextBoxFor(m => m.saldo, new { @id = "Saldo", @class = "input-login", @readonly = "readonly" })
                                    @Html.HiddenFor(m => m.idTransaccion, new { @id = "idTransaccion" })
                                </td>
                            </tr>

                        </table>
            </center><br>
            <center>
                <table width="122" border="0" align="center" cellspacing="10">
                    <tr>
                        <td width="51"><a onclick="EnviarMensajes()" class="boton-para-enviar" style="margin:auto">Aprobar</a></td>
                        <td width="37"><a href="#" class="boton-para-NO-enviar" style="margin:auto">Rechazar</a></td>
                    </tr>
                </table>
            </center>
            <br>
            <strong>Nota:</strong> Si el saldo no se encuentra completo para la cantidad total de mensajes, los mensajes que queden pendientes se enviarán cuando realice la recarga.
        </div>
    </div>
</div>

检查控制器:

public ActionResult EnviarMensajeIndividual(MensajesEntity model)
        {
            InformacionEntity Info = new InformacionEntity();
            Info.error = false;
            model.usuarioCreacion = User.Identity.Name;

            if (HttpContext.Session["Lista"] != null && model.mensaje != null)
            {
                List<ContactoEntity> lista = HttpContext.Session["Lista"] as List<ContactoEntity>;

                int idTransaccion = mdm.EnviarMensajes(model, lista, 1);
                if (idTransaccion > 0)
                {
                    Info = mdm.InformacionDeEnvio(idTransaccion);
                    Info.error = false;
                }
                else
                {
                    //error
                    Info.error = true;
                    Info.mensajeError = "error.";
                }
            }
            else
            {
                // tiene q tener contactos agregados
                Info.error = true;
                Info.mensajeError = "error";
            }
            var js = new JavaScriptSerializer();
            var Data = new ContentResult();
            js.MaxJsonLength = Int32.MaxValue;
            Data.Content = js.Serialize(Info);
            Data.ContentType = "application/json";

            return Data;
        } 

【问题讨论】:

  • 如果@ 符号在if 语句之前,则不需要在Model 之前使用@ 符号。
  • 由于您的视图在顶部有这个..@model SeaConnectionManager.Modelos.EnvioMensajes.InformacionEntity.. 它需要一个InformacionEntity.. 类型的对象,所以你必须给它那个对象.. 在你的控制器中是InformacionEntity Info = new InformacionEntity();.. 所以return View(Info);
  • 您发布的操作甚至不会返回视图,因此如果您走得足够远以至于看到 Model 在您的视图中为空,那么它显然不是正确的。
  • 属性不是属性。请不要混淆两者。

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

你的模型被赋予 null 值的原因是因为在你的视图顶部你有这个:

@model SeaConnectionManager.Modelos.EnvioMensajes.InformacionEntity‌​

因此,您的视图期待InformacionEntity 类型的对象。

但是,在您应该将该对象返回到视图的控制器中,您并没有返回 InformacionEntity 对象。

所以在你的控制器中,你有这个:

InformacionEntity Info = new InformacionEntity();

这是你需要返回的。

因此,将您的退货声明更改为:

return View(Info);

如果这有帮助,请告诉我!

【讨论】:

  • 谢谢!对我帮助很大!
【解决方案2】:

从模型中删除@

@if (Model != null) { 
                        if (Model.cantidadMensajes >= 5)
                        {
                            for (var i = 1; i <= 5; i++)
                            {
                                <li><a href="#tabs-@i"> @i</a></li>
                            }
                        }
                        else { 
                            for (var i = 1; i <= Model.cantidadMensajes; i++)
                            {
                                <li><a href="#tabs-@i"> i</a></li>
                            }                
                        }
                    }

【讨论】:

  • 谢谢,我试过了,但没有成功。
【解决方案3】:

您的视图的模型类型是 SeaConnectionManager.Modelos.EnvioMensajes.InformacionEntity‌​

这意味着应该使用该类型的对象来渲染视图。

您的控制器操作表明您根本没有返回视图。相反,您正在返回 ContentResult。内容结果无法转换为视图预期的模型类型。这就是为什么您的模型始终为 null 并且您没有进入“if (Model != null)”块的原因。

您需要对控制器操作进行以下更改。

public ActionResult EnviarMensajeIndividual(MensajesEntity model)
    {
        InformacionEntity Info = new InformacionEntity();
        Info.error = false;
        model.usuarioCreacion = User.Identity.Name;

        if (HttpContext.Session["Lista"] != null && model.mensaje != null)
        {
            List<ContactoEntity> lista = HttpContext.Session["Lista"] as List<ContactoEntity>;

            int idTransaccion = mdm.EnviarMensajes(model, lista, 1);
            if (idTransaccion > 0)
            {
                Info = mdm.InformacionDeEnvio(idTransaccion);
                Info.error = false;
            }
            else
            {
                //error
                Info.error = true;
                Info.mensajeError = "error.";
            }
        }
        else
        {
            // tiene q tener contactos agregados
            Info.error = true;
            Info.mensajeError = "error";
        }
        return View(Info);

    }

这里我假设您的视图名称与您的操作名称相同。

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多