views:

42

answers:

2

Hi,

Could you you tell me the best way to get data from UI to send them to the controller. What do you think a bout the code below ? Is there an another solution without all this javascript/jquery/ajax code ?

Thanks,

function CustomerAddSave() {
    $('#btSave').bind('click', function (event) {
        $.ajax({
            type: "POST",
            url: "/Customer/CustomerSave",
            data: {
                id: $('#Id').val(),
                firstName: $('#FirstName').val(),
                lastName: $('#LastName').val(),
                isEnable: $('#IsEnable').attr('checked')
            },
            success: function (html) {
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) { }
        });
    });
}
A: 

If you don't want to use JavaScript then you can use the HttpPost attribute within your Controller Class.

e.g

    public class HomeController
    {



    public ActionResult Contact()
    {

       return View()

    }


    [HttpPost]
    public ActionResult Contact(FormCollection values)
    {

     //Code to update here


    }


}

Any HTML Get request will call the standard Contact() method. Any HTML Post will call the Contact() method marked with [HttpPost]

Barry
+2  A: 

If Your form contains valid input fields, You could use serialize function.

It would look like this:

$.ajax({
  type: "POST",
  url: "/Customer/CustomerSave",
  data: {$("#myUberForm").serialize()},
});

It is possible to serialize anything too (not just forms).

Arnis L.