Best Pattern/Practice MVVM page

2 posts, 0 answers
  1. Chad
    Chad avatar
    7 posts
    Member since:
    Oct 2014

    Posted 15 Feb Link to this post

    I have a detail page with an edit button that will load a modal for editing the content. I have thought of 3 ways to handle this and am looking for the best solution. 

     

    The view returns the object and so right now I have: 

    @Html.TextboxFor(m => m.ContactName, new { @data_bind = "value: contactName"})

     

    In the javascript I have:

     var contactViewModel = kendo.observable({
        contactName = $('#ContactName').val()

    }

    My question is: What is the best way to load a page using MVVM. Or what is the preferred pattern:

     

    1. Just like I have above. am passing the model to the view from the action and using the html wrappers. I then set the values of the viewmodel to the same input (this seems like it could cause recursive issues?)

    2. i create hidden form fields for the initial value and then use an init function I would call on page load that loads the elements. 

    @Html.HiddenFor(m => m.ContactName)

    <input data-bind="value: contactNmae" />

      var contactViewModel = kendo.observable({
        contactName = null,

        init = function() {

             contactViewModel.set("contactName", $('#ContactName').val();

        }
    }

    3. I would just return an empty view and then use an ajax call to load the viewmodel:

    <input data-bind="value: contactName" />
      var contactViewModel = kendo.observable({
        contactName = null,
        init = function() {

             $.ajax(options).done(function (data) {
                    if (data.success === true) {
                        contactViewModel.set("contactName", data.contactName;
                });
             
        }
    }

     

    I know all 3 of these are valid options. I guess my question is really what is the preferred way or recommended way of loading a page and using the mvvm pattern with the Kendo library? 

  2. Daniel
    Admin
    Daniel avatar
    2117 posts

    Posted 18 Feb Link to this post

    Hello Chad,

    The simplest option would be to load the model via Ajax because this will allow you to initialize the ViewModel with a single call if you have many fields:
    $.ajax(options).done(function (data) {
        if (data.success === true) {
            var contactViewModel = kendo.observable(data.model);
            kendo.bind($("selector"), contactViewModel);
        }
    });
    but any of the described options can be used. Another possible solution if the script is used inside the MVC view is to directly output the View model:

    var contactViewModel = kendo.observable(@Html.Raw(Json.Encode(Model)));


    Regards,
    Daniel
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
  3. Kendo UI is VS 2017 Ready
Back to Top