0

Hello I currently have an application that uses MVC 5 and Entity Framework 6. I have a view with the current code:

<tr>
  <td class="infoCell">@Html.LabelFor(x => Model.PersonInfo.firstName, "First Name:")</td>
  <td class="infoCell">@Html.EditorFor(x => Model.PersonInfo.firstName)</td>
  <td class="infoCell">@Html.LabelFor(x => Model.PersonInfo.lastName, "Last Name: ")</td>
  <td class="infoCell">@Html.EditorFor(x => Model.PersonInfo.lastName)</td>
</tr>

I also have a controller method with the code:

[HttpPost]
public ActionResult Save(PersonViewModel PersonViewModel)
{
  PersonService PSVC = new PersonService();
  PSVC.Save(PersonViewModel.PersonInfo, PersonViewModel.ModeInfo, PersonViewModel.PersonISS, PersonViewModel.Injury);
  using (MEDICSContext db = new MEDICSContext())
  {
    db.SaveChanges();
  }
  return PartialView("_People");
}

This controller is calling my service method Save with the code:

public void Save(PersonInfo PersonInfo, PersonModeInfo PersonModeInfo, PersonISS PersonISS, Injury Injury)
{
  using (MEDICSContext db = new MEDICSContext())
  {
    db.Entry(PersonInfo).State = EntityState.Modified;
    db.Entry(PersonModeInfo).State = EntityState.Modified;
    db.Entry(PersonISS).State = EntityState.Modified;
    db.Entry(Injury).State = EntityState.Modified;
    db.SaveChanges();
  }
}

I want to set up a button in the view that will save any changes i make in the "editorFor" fields without leaving the view. Im not entirely sure how to tie a button to the action in the controller and how to update the page without having to reload the page. Any help is much appreciated.

Ɖiamond ǤeezeƦ
  • 3,223
  • 3
  • 28
  • 40
Matthew Czajka
  • 159
  • 1
  • 2
  • 17
  • Take a look at [`Ajax.BeginForm()`](http://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor), it might be what you're looking for – Thiago Ferreira Mar 03 '16 at 14:57
  • i am using "@using (ajax.beginform("save", "people", new ajaxoptions() { httpmethod = "POST" }, new { id = model.personInfo.personNumber } ))" – Matthew Czajka Mar 03 '16 at 15:03

2 Answers2

0

Do this with a jquery Ajax call. In your page script add an event for you button

$("#myButton").click(function () {
        $.ajax({
        type: "POST",
        url: "/Save",
        data: $('#myForm').serialize(),
        datatype: "html",
        success: function (data) {
            alert('saved !');
        }
});

});

You will need to have a form on your page called #myForm or whatever you want to call it.

James Dev
  • 2,979
  • 1
  • 11
  • 16
  • is there a way to add an ID to a razor tag so i can add it to #myForm? how do you suggest i add the data fields to the #myForm? – Matthew Czajka Mar 03 '16 at 15:25
  • If your data is surrounded by the html form tag then every input within that form tag will be posted to the controller. The data should map to your viewmodel by binding directly. – James Dev Mar 03 '16 at 15:28
0

Use AJAX to submit your data. The following example uses jQuery 1.7.1. Attach this function to your client side click handler

$.ajax({
    url: '@Url.Action("SomeAction", "SomeController")',
    type: 'POST',
    data: GlobalJsHelpers.getFormData($('form')),
    success: function(resultData) {
        // POST was sucessful, do something 
    }
});

data must be JSON data of your form, you can use the following helper:

var GlobalJsHelpers = GlobalJsHelpers || {};

GlobalJsHelpers.getFormData = function (forms) {
    var formElements = GlobalJsHelpers.getFormDataElements(forms);
    return GlobalJsHelpers.createJsonObjectFromElements(formElements);
};
GlobalJsHelpers.getFormDataElements = function (forms) {
    // find all input, textarea, select and button elements which are not disabled
    // and if they are a checkbox they must be checked to be included (required due to mvc checkbox behaviour with hidden field)
    // and if there are radio buttons, only take the :checked radiobutton
    return $(forms).find(':input[name]:not(:disabled)').filter(':not(:checkbox, :radio), :checked');
};
GlobalJsHelpers.createJsonObjectFromElements = function(formElements) {
    // create array of objects (in a style understandable by the MVC modelbinder)
    if (formElements.length === 0)
        return ({});

    return formElements.map(function () {
        var input = $(this);
        return { name: input.attr('name'), value: input.val() };
    });    
};
Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36