0

I'm working with MVC 4 web app conecct to a SQL DB on my server.

I have a page(for admin to control users managment) with a list(table) of users, each row represent a user with the fields :

  1. User Name
  2. Date Created
  3. Role
  4. Email
  5. Status

And each row have 3 button in right side :

  1. Deactivate
  2. Edit(Role)
  3. Delete User

A user can be active & unactive (freeze user account temporarily) using the button "Deactivate".

When you press the "Deactivate" button the user status changes to "unactive" and the button value(text) is changes to "Active", using Jquery.

Now i want to be able to call a function(server side) when the" Activate/Deactivate" button is clicked in order to update the DB, but i dont want to call a function on the controller and return the same view and force the page to post back, i want to update the DB only without any changes in the presentation layer(changing view and etc) because i take care of the presentation layer with help from Jquery.

How Can I Do It?

The code:

A row in my table:

 <tr>
    <td width="15%">@appUser.name</td>
   <td class="text-left" width="15%">@appUser.date</td>
   <td class="text-left" width="10%">@appUser.role</td>
   <td id="user_email" class="text-left" width="24%">@appUser.email</td>
    @if(appUser.activeStatus)
    {
      <td class="text-left" width="10%"><span id=@Url.Content("status_lbl" + index) class="label label-success">Active</span></td>
      <td class="btn-group-sm text-center ">
        <input id="@Url.Content("freeze_btn" + index)" value="Deactivate" class="btn btn-default" onclick="@Url.Action("SetActive", "Home", new { email = appUser.email, activeStatus = false }) " />

     }
     else
     {
       <td class="text-left" width="10%"><span id=@Url.Content("status_lbl" + index) class="label label-danger">Unactive</span></td>
       <td class="btn-group-sm text-center ">
       <input id="@Url.Content("freeze_btn" + index)"  value="Activate" class="btn btn-default" onclick="@Url.Action("SetActive", "Home", new { email = appUser.email, activeStatus = false }) "  />

     }
  <input type="button" value="Edit" class="btn btn-default " />
  <input type="button" value="Delete" class="btn btn-default " />
   </td>
   </tr>

Jquery: (Taking care of the presentation)

    $('input[id^=freeze_btn]').click(function (event) {
    var btn = $(event.target);
    var text = $(this).attr('value');
    var newid = $(this).attr('id').replace('freeze_btn', 'status_lbl');
    if (text == "activate ") {
        btn.val("Deactivate");
        $('#' + newid).removeClass("label-danger").addClass("label-success").text("Active");
        $(this).attr('onclick').replace('true', 'false');
    }
    if (text == "Deactivate") {
        btn.val("activate ");
        $('#' + newid).removeClass("label-success").addClass("label-danger").text("Unactive");
        $(this).attr('onclick').replace('false', 'true');
    }  
});

How can i call a function(code behind) with the the paramters

  1. User Email(in order to search the user in my DB
  2. The value(text) of the button "Active/Deactivate" (so i will know if to activate the user or to Deactivate without accessing the DB in order to check the user current status because i do it once the page load (not implemented yet))

And stay on the view, no return view just a function working in bacgground updating the database nothing more.(This is very important!)

Ron
  • 1,744
  • 6
  • 27
  • 53
  • What you mean ? can you give me a little bit explaining so ill know what exactly im looking for ?? – Ron Aug 19 '14 at 10:43
  • sergey has already provided you the approach. you just need to use ajax methods. so that page don't get load and you can simultaneously call backend methods – Kamlesh Arya Aug 19 '14 at 10:45

2 Answers2

0

Just example:

Create result action in controller:

[HttpPost]  
public ActionResult GetSomethingForSomething(Type someModel)  
{            
   // Do what you want
   return Json(your_model, JsonRequestBehavior.DenyGet);
}

And use it on view:

$.ajax({
         url: '/Controller/GetSomethingForSomething',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         success: function (result) {
            // do success
         },
         error: function (xhr) {
            alert('Error');
         },
         async: true
      });

Then on success update what you want.

Another example: http://bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/

Sergey Shabanov
  • 176
  • 2
  • 11
  • Sergey i dont need to define model of the pass data ? like this : https://www.youtube.com/watch?v=NBVsHuc3OIE and one last question: Does its safe to pass data to the server side this way ? its not a security loop hole ? – Ron Aug 19 '14 at 13:13
  • If you do not need any model use another "data" like here in answer: http://stackoverflow.com/questions/2002163/jquery-ajax-call-data-parameters-are-not-being-passed-to-mvc-controller-action – Sergey Shabanov Aug 20 '14 at 01:57
0

You can use AJAX. Below is an simple example might help using MVC action too:

var path = '@Url.Action("DoSomethingAction", "DoSomethingController")';
                var paramsObject =
                {
                    Email: .....,
                    IsActive : .....,
                };

                $.post(path, paramsObject, function (result) {
                    if (result.Errors) {
                        $.each(result.Errors, function (index, item) {

                        });
                    }
                    else {

                    }

                }).error(function (error) {
                    alert("Error Occured " + JSON.stringify(error));                    
                });

and on the server side you have the action controller that will handle that request and return a JSON Result with operation success or not or even errors

Samer Aburabie
  • 248
  • 2
  • 8
  • And this safe to pass data from javascript(ajax) to the conroller this way ? because i heard its a security loop hole... – Ron Aug 19 '14 at 13:12
  • This is the normal way of doing it, now you can put extra security precautions on your code, but i suggest you to worry about things when you know them for sure. – Samer Aburabie Aug 19 '14 at 13:44