0

I have form with a lot of inputs:

<input type="text" id="SomeName1" name="SomeName1" />
<input type="text" id="SomeName2" name="SomeName2" />
etc...

All these inputs are part of my viewmodel:

public class MyViewModel
{
    public string SomeName1 { get; set; }
    public string SomeName2 { get; set; }
    //etc...
}

I need to refresh all those inputs without refreshing whole page, so I need to use Ajax request. However the problem is that we need explicitly define viewmodel in Javascript and send it via jquery.ajax, like 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 is a lot of copy-paste code, which is hard to edit and support.

I don't want explicitly send data, like in example, from all inputs and then explicitly set new data to all that inputs.

What should I do with this?

Yurii N.
  • 5,455
  • 12
  • 42
  • 66

1 Answers1

0

Based on mayk's answer, which give me idea how can I 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 a = 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 your form to

var viewModel = 
{
    SomeName1: $("#SomeName1").val(),
    //etc...
}

Javascript object, then send viewmodel to your controller, which returns this viewmodel again. Returned viewmodel simply applies to each input in form with corresponding names.

Yurii N.
  • 5,455
  • 12
  • 42
  • 66