Search code examples
asp.net-mvcknockout.jsknockout-mapping-plugin

how to add an observable property to a knockout.mapping loaded from mvc 4 class


I'm working with mvc4 and knockout trying to understand all the cool stuff you can to with it.

the thing is, i have this code which loads info and sends it to the view.

public ActionResult AdministraContenidoAlumno()
{
Alumno NuevoAlumno = new Alumno();
            NuevoAlumno.AlumnoId = 1;
            NuevoAlumno.NombreCompleto = "Luis Antonio Vega Herrera";
            NuevoAlumno.PlanEstudioActual = new PlanEstudio
            {
                PlanEstudioId = 1,
                NombrePlan = "Ingenieria en sistemas",
            ListaMateriasPlan = new List<Materias> {
                        new Materias{MateriaId=1,NombreMateria="ingenieria 1"},new Materias{MateriaId=2,NombreMateria="Ingenieria 2"}
                }
        };
        return View(NuevoAlumno);

Basically, create a new object alumno, who contains a PlanEstudio, who contains a list of Materias, then send it to the view.

In the view i have this.

@model MvcRCPG.Models.Alumno

@{
    ViewBag.Title = "AdministraContenidoAlumno";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
    var data;
    $(function () {
        var jsonModel =             '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(this.Model))';
        var mvcModel = ko.mapping.fromJSON(jsonModel);
        data = mvcModel;
        ko.applyBindings(mvcModel);
    });
    function Guardar() {
        $.ajax({
            url: "/DemoKnockuot/GuardarAlumno",
            type: "POST",
            data: JSON.stringify({ 'NuevoAlumno': ko.toJS(data) }),
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                if (data == "Success") {
                    alert('entro')
                } else {
                    alert('trono')
                }
            },
            error: function () {
                alert("An error has occured!!!");
            }
        });
    }
</script>

With the mentioned above functions i can read and send data to the server and do stuff on the controller, however i need to add remove or manipulate the information in the view.

So the question is: how do i add a function to 'mvcModel' in order to push a new "materia" in the ListaMateriasPlan object?

Thank you, and if you have more tips in order to understand it better i appreciate your help.


Solution

  • The mvcModel created by the mapping plugin will have observable properties.

    For example, to add a new "materia" do something like:

    function Materias() {
      this.MateriaId = ko.observable();
      this.NombreMateria = ko.observable();
    }
    
    var newItem = new Materias();
    newItem.MateriaId(3);
    newItem.NombreMateria("Ingenieria 3");
    
    mvcModel.PlanEstudioActual.ListaMateriasPlan.push(newItem);
    

    And normally, you would wrap the "adding" logic as a method in a view model.