0

I have a view which asks for user input. View is as below -

 @(Html.Input(m => m.SchoolName).Id("SchoolName"))
 @(Html.Input(m => m.Address).Id("Address"))
 @(Html.Input(m => m.Phone).Id("Phone"))

 <button class="btn btn-primary" name="btnSchoolSave" id="btnSave">
             Submit
 </button>

Then I have a javascript function, which handles the click event of the button -

function () {
            $("button[name='btnSchoolSave']").on('click', function () {                
                $.ajax({
                            url: '/School/SaveSchool',          //School is my controller and 'SaveSchool' is the method in the controller.
                            contentType: 'application/html; charset=utf-8',
                            type: 'POST',
                            dataType: 'html'
                       })
                        .success(function (result) {
                            alert("saved")
                        })
                        .error(function (xhr, status) {
                            alert(status);
                        })
            })
        };  

My Controller method is like below. I have not implemented the method yet.

 public void SaveSchool(Models.School model)
 {
   //TODO
 } 

My idea is - I want to get all the values inputted by the user in the View, get all those Model values, and pass it to Javascript function and javascript function in return passes the Model to the controller method and save it.

Now, I know that I can directly call my Controller action method from the view and get the saving of data taken care of. But, my requirement is to pass the data to javascript and from javascript call the method and save user input.

How can I do that?

Thanks

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Kristy
  • 279
  • 6
  • 18
  • Read each input value and build a js object matching your c# class structure and send it via ajax. You can also try to serialize your form and send it. Have you tried any of these ? – Shyju Mar 15 '17 at 20:50
  • I have not. Can you give a sample code please. – Kristy Mar 15 '17 at 20:51
  • 1
    This might help you to get started http://stackoverflow.com/questions/20226169/how-to-pass-json-post-data-to-web-api-method-as-object/20226220#20226220 – Shyju Mar 15 '17 at 20:52
  • and this too http://stackoverflow.com/questions/10803292/how-to-send-data-in-jquery-post-to-mvc-controller-which-use-viewmodel-as-paramet/10803473#10803473 – Shyju Mar 15 '17 at 20:52
  • Thank You for referring those posts. I think 2nd link will help me get the required result. I am unable to understand, $("#formId") part there. What is that referring to there? – Kristy Mar 15 '17 at 21:02
  • That is a jQuery selector to get a hold of the form tag (with id="formId") – Shyju Mar 15 '17 at 21:03
  • $.post("Yourcontroller/YourAction", $("#formId").serialize() ,function(data){ I am talking about this code there. So, formId I am assuming is the id of the form, how do I define it in my view? Also, my view is partial view. – Kristy Mar 15 '17 at 21:04
  • You have to keep your input fields inside a form. – Shyju Mar 15 '17 at 21:05
  • I am able to get that working with the first link you provided me. Thank You! :) – Kristy Mar 16 '17 at 16:35

1 Answers1

0
@model XXX.YourViewModel

<form id="your-form" style="margin: 0px;">
    @Html.AntiForgeryToken()

    @Html.HiddenFor(m => m.Id)

    @Html.LabelFor(m => m.SchoolName)
    @Html.TextBoxFor(m => m.SchoolName)
    @Html.ValidationMessageFor(m => m.SchoolName)

    @Html.LabelFor(m => m.Address)
    @Html.TextBoxFor(m => m.Address)
    @Html.ValidationMessageFor(m => m.Address)

    @Html.LabelFor(m => m.Phone)
    @Html.TextBoxFor(m => m.Phone)
    @Html.ValidationMessageFor(m => m.Phone)

    <button id="btnSchoolSave" name="edit" type="button">Save</button>
</form>

$("#btnSchoolSave").on('click', function () {                
    //get the form
    var form = $("#your-form");

    //validate form
    if (!form.valid()) {
        return;
    }

    //serialize the form
    serializedForm = form.serialize();

    //ajax post
    $.ajax({
        url: "@Url.Action("CompanyEdit", "CV")",
        type: "POST",
        data: serializedForm
        .........
        ......

Now the serializedForm will be posted to your controller parameter as the ViewModel

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSchool(YourViewModel modal)
{
    //find school
    var school = repository.FindSchool(modal.Id)

    //map value from modal
    school.SchoolName = modal.SchoolName;
    ..........

    repository.SaveScool(school);
}
Mindless
  • 2,352
  • 3
  • 27
  • 51