c# - Sending Ajax request to controller implicitly in Asp.Net -


i have form lot of inputs:

<input type="text" id="somename1" name="somename1" /> <input type="text" id="somename2" name="somename2" /> etc... 

all these inputs part of viewmodel:

public class myviewmodel {     public string somename1 { get; set; }     public string somename2 { get; set; }     //etc... } 

i need refresh inputs without refreshing whole page, need use ajax request. problem need explicitly define viewmodel in javascript , send via jquery.ajax, this:

var viewmodel =  {     somename1: $("#somename1").val(),     //etc... } var request = $.ajax({     url: '@url.action("updateaction", "somecontroller")',     type: "post",     cache: false,     data: viewmodel,     datatype: "json" }) request.done(function (data) {     $("#somename1").val(data.somename1);     //etc...                                    }) 

so, there lot of copy-paste code, hard edit , support.

i don't want explicitly send data, in example, inputs , explicitly set new data inputs.

what should this?

based on mayk's answer, give me idea how can solve it, i've written simple solution:

var viewmodel = $("#myformid").serializeobject(); var request = $.ajax({     url: '@url.action("updateaction", "somecontroller")',     type: "post",     cache: false,     data: viewmodel,     datatype: "json" }) request.done(function (data) {        $.each(data, function (key, value) {            $("#myformid) input[name=" + key + "]").val(value);        });                                }) 

where:

$.fn.serializeobject = function () {     var o = {};     var = this.serializearray();     $.each(a, function () {         if (o[this.name] !== undefined) {             if (!o[this.name].push) {                 o[this.name] = [o[this.name]];             }             o[this.name].push(this.value || '');         } else {             o[this.name] = this.value || '';         }     });     return o; }; 

serialize form

var viewmodel =  {     somename1: $("#somename1").val(),     //etc... } 

javascript object, send viewmodel controller, returns viewmodel again. returned viewmodel applies each input in form corresponding names.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -