How to use JSON data in a view?

2020-08-04 10:11发布

问题:

I am using now the following code in my Edit button in the flexigrid:

var url = '/Client/Details/' + id ;
$.getJSON(url, function (data) {
    //  setFormControls(data.Id, data.Role, data.Location, data.JobType, data.Description);
    alert(data);
});
//location.replace(url);
RunModalDialog("Edit Client: " + ClientName);

And my form is a bit complex view like this

@model CardNumbers.Models.ClientViewModel
 @using (Html.BeginForm(null, null, FormMethod.Post, new { id = "sform", title = "Client Info" }))

 {    
  <fieldset>
    <legend>Client Info</legend>

    @Html.ValidationSummary(true)

    @Html.HiddenFor(m => m.ClientId)
    @Html.EditorFor(m => m.Number, EditorTemplate.TextBox)

    @Html.EditorFor(m => m.Name, EditorTemplate.TextBox)

    @Html.EditorFor(m => m.Client.Address, EditorTemplate.EditBox)

...

where EditorFor is a custom EditorFor. So, it will be a bit hard to manually translate returned json data into forms properties. I am wondering may be there is some simple method to do this kind of translation? I looked into knockout.js but I am not using it in my project (yet), so I am wondering if there is anything else?

Thanks in advance for help.

UPDATE. Just to make my question clearer I am adding a bit more info.

My main view is:

@model CardNumbers.Models.ClientViewModel

   @section scripts {
    <script src="@Url.Content("~/Scripts/Clients.js")" type="text/javascript" ></script>
    }

   <form id="frmClientsSearch">
    <label for="clientNo">Client No: </label>
    <input type="number" name="searchClientNo" class="numericOnly" /><br />
    <label for="clientName">Client Name: </label>
    <input type="search" size="25" value="Please enter the search value"      class="SelectOnEntry"
        name="searchClientName" />

       <input type="button" id="btnClientsSearch" value="Find / Refresh" />
    </form>
    <div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;"    id="ClientsResults">
    <table id="flexClients" style="display: none">
       </table>
    </div>

    <div id="editor" style="visibility:hidden">
       @Html.Partial("_ClientForm", Model);
    </div>

And my js file has the following:

    var $dlg = $("#sform").dialog({
    autoOpen: false,
    show: "blind",
    closeOnEscape: true,
    resizable: true,
    width: 1200,
    height: 750,
    minHeight: 600,
    minWidth: 950
    });

    function RunModalDialog(title, url)
{    
    if (title)
        $dlg.dialog("option", {"title": title });

    if (url)
    {        
        $dlg.load(url).dialog("option", { "title": title }).dialog("open");
    }
        //$dlg.load(url, function () {
        //    var validator = $("#sform").validate();
        //    if (validator)
        //         validator.resetForm();
        //    $dlg.dialog("option", { "title": title }).dialog("open");
        //});
    else {
        var validator = $("#sform").validate();
        if (validator)
            validator.resetForm();
        $dlg.dialog("open");
       }
    }

    function add(com, grid) {
    $('#fntype').val('Add');
    var url = '/Client/Add/'
    //location.replace(url);
    RunModalDialog("Create New Client");

   // clearForm();

   }

     function edit(com, grid)
      {
        $('.trSelected', grid).each(function () {

                var id = $(this).attr('id');
                id = id.substring(id.lastIndexOf('row') + 3);
                currentId = id;
                $('#fntype').val('Edit');
                var ClientName;
                ClientName =$('.trSelected td:eq(2)').text();
                var url = '/Client/Edit/' + id ;

                $.getJSON(url, function (html) {
                    //  setFormControls(data.Id, data.Role, data.Location, data.JobType, data.Description);
                    // alert(data);
                    $('#editor').html(html);
                });
               //location.replace(url);
               RunModalDialog("Edit Client: " + ClientName);
        });

    }

And now I see the same behavior for Add and Edit, e.g. Edit does not show data. What I see now http://www.universalthread.com/Thread%20photos/2013/01562893.jpg

回答1:

If you want to make it easier, simply put the code you have shown in a partial view and then have the Details controller action return this partial view. Now when you invoke this action with AJAX it will return the updated contents of the partial that you could directly replace in your DOM. This way you don't need to be bothering with binding the JSON values to your form elements.

public ActionResult Details(int id)
{
    ClientViewModel model = ...
    return PartialView(model);
}

and then:

var url = '/Client/Details/' + id ;
$.getJSON(url, function (html) {
    $('#someContainerDiv').html(html);
});

#someContainerDiv used in my example will obviously be defined in your main view:

<div id="someContainerDiv">
    @Html.Partial("Details", Model)
</div>

The partial will then contain the form you have shown in your question.



回答2:

With Jazzen Chen help we solved this problem. All I needed to change is to use get instead of getJSON in the above. Now my form shows up with data correctly.