In my view I have the following code which is loaded with properties from an object, which display just fine when I run my project.. But, how can I access the properties of that object in Jquery? Currently what I am getting from the console.logs is undefined.
Edit: I tried adding @Html.Raw(Json.Encode(Model) to my view and I can now see every prop of the object when I hit inspect in the html, but I still can´t access em in jquery.
function EditTrabajoEnColegio(li) {
console.log(li); //this displays the entire li in the console.
//From here, I get all as undefined
console.log(this.TrabajoId);
console.log(li.contrato);
console.log(li.mesIngreso);
console.log(li.anioIngreso);
console.log(li.esTitular);
console.log(li.cargoColegio);
console.log(li.sueldoBruto);
}
<li id="li-@Model.TrabajoId" class="list-group-item"
onclick="EditTrabajoEnColegio(this)">
@Model.MesIngresoStJohns/@Model.AnioIngresoStJohns
-
@(Model.AnioEgresoStJohns != null ?
Model.MesEgresoStJohns.ToString() + "/" +
Model.AnioEgresoStJohns.ToString() : "Actualidad")
-
@Model.SedeNombre
Model.TipoDocenteId
Model.TieneContrato
@Model.CargoColegio
@Html.HiddenFor(x => x.TrabajoId)
@Html.HiddenFor(x => x.SedeId)
@Html.HiddenFor(x => x.AnioEgresoStJohns)
@Html.HiddenFor(x => x.AnioIngresoStJohns)
@Html.HiddenFor(x => x.MesIngresoStJohns)
@Html.HiddenFor(x => x.MesEgresoStJohns)
@Html.HiddenFor(x => x.FechaIngreso)
@Html.HiddenFor(x => x.FechaEgreso)
@Html.HiddenFor(x => x.SedeNombre)
@Html.HiddenFor(x => x.CargoColegio)
@Html.HiddenFor(x => x.TipoDocenteId)
@Html.HiddenFor(x => x.EsTitular)
@Html.HiddenFor(x => x.TieneContrato)
@Html.HiddenFor(x => x.SueldoBruto)
</li>
}
Any help will be apreciated.
To future readers, I was able to resolve it.
What I did was,
JSON.parse('@Html.Raw(Json.Encode(Model))');That allowed me to pass the defined object
And in jquery
Note that the name of the parameter does not matter in jquery, it´s just something that you get from the view.
Your requirement is not very clear in the question, however what you are doing in the javascript is wrong.
here
this
refers to theli
object you create with razor. Therefore in the functionEditTrabajoEnColegio
li
object will store theli
element you passonclick
event. So even though you get a result fromconsole.log(li)
(it will print the entire li object), it will not show any values toconsole.log(this.TrabajoId)
('TrabajoId' is not a property of the li object, it is an attribute from your Model).Accessing Model data is also possible by,
you can now play with all the values from the Model with
data
variable just as you use a normal Json object..You need to use a javascript or jquery function such as find()
Or something like :