TheBoubou
TheBoubou

Reputation: 19903

Data from UI to Controller in ASP.NET MVC

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) { }
        });
    });
}

Upvotes: 1

Views: 165

Answers (2)

Arnis Lapsa
Arnis Lapsa

Reputation: 47597

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).

Upvotes: 2

codingbadger
codingbadger

Reputation: 43984

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]

Upvotes: 0

Related Questions