How to create an input (editorfor) for a field not in the model

396 Views Asked by At

I have the following on my EDIT view

@model Inspinia_MVC5.Areas.GlobalAdmin.Models.Empresa
@{
    ViewBag.Title = "Edit";
    Layout = "~/Areas/GlobalAdmin/Views/Shared/_LayoutGlobalAdmin.cshtml";
    var camposAdicionalesEmpresa = (List<Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad>)ViewData["CamposAdicionalesEmpresa"];
    var valoresCampoAdicionalesEmpresa = (Dictionary<string, string>)ViewData["ValoresCampoAdicionalesEmpresa"];

}

and my controller is like this:

public ActionResult Edit(int? id)
{
    var listFields = from b in db.Propiedades
                     where b.Entidad.Nombre == "Empresa"
                     select b;
    ViewData["CamposAdicionalesEmpresa"] = listFields.ToList<Propiedad>();
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Empresa empresa = db.Empresas.Find(id);
    if (empresa.PropiedadesExtra != null)
    {
        XElement xmlTree = XElement.Parse(empresa.PropiedadesExtra);
        Dictionary<string, string> dict = new Dictionary<string, string>();
        foreach (var el in xmlTree.Elements())
        {
            dict.Add(el.Name.LocalName, el.Value);
        }
        ViewData["ValoresCampoAdicionalesEmpresa"] = dict;
    }
    if (empresa == null)
    {
        return HttpNotFound();
    }
    return View(empresa);
}

ViewData["ValoresCampoAdicionalesEmpresa"] is a dictionary with key values, and I need to display in an input form that value.

On my razor view I have this

@if (valoresCampoAdicionalesEmpresa != null)
{
    <div class="panel panel-default">
        <div class="panel-heading">Propiedades adicionales</div>
        <div class="panel-body">               
            @foreach (Inspinia_MVC5.Areas.GlobalAdmin.Models.Propiedad propiedad in camposAdicionalesEmpresa)
            {
                if (propiedad.TipoDeDatos == "Texto")
                {
                    var valor = valoresCampoAdicionalesEmpresa.Where(p => p.Key == propiedad.Nombre).First().Value;
                    <div class="form-group">
                        @Html.Label(propiedad.Nombre, new { @class = "control-label col-md-2" })
                        <div class="col-md-10">
                            @Html.Editor(valor)
                            @*@Html.ValidationMessageFor(prop => propiedad.)*@
                        </div>
                    </div>
                }
            }
        </div>
    </div>
}

If I debug, the valor variable is correctly set, however on the user interface, the textbox is empty.

How can I achieve that?

1

There are 1 best solutions below

0
On BEST ANSWER

If you have no particular reason for using editor then replace @Html.Editor(valor) with

@Html.TextBox("TextBoxName",valor)