0

I am working on mvc4 project.I am using Dexexpress grid. What i want to do is when i click on add .. i do ajax call to check if user is in database..if not its saved into database and .. and i am returning paritial view of grid to refresh grid with latest data.

But i want to return some value too along with gridview partial.. so that i can show whther that user is already added or not.

Eg : Jquery code for ajax call

function AddUser() {
    showProgress();
    $.ajax({
        url: 'ManageUsers/AddUsers/?id=' + Math.random(),
        data: $("#frmManageUsers").serialize(),
        type: 'Post',
        datatype: 'json',
        success: function (data) {
            if (data != '') {                
                $("#grid").html('');
                $("#grid").html(data);
            }
            else
                alert('No Record Found');
        },
        error: function (request, status, error) { ShowErrorMessage(); },
        complete: function () { hideProgress(); ShowSuccessMessage(); }
    });
}  

and controller

public ActionResult AddUsers(Usertable model)
        {
            int successid = ManageUserExecutor.Save(model);
            if (successid == -1)
            {
                List<usp_GetListOfUsers_Result> objList = new List<usp_GetListOfUsers_Result>();
                return PartialView("GridViewPartial", objList);
            }
            else
                return RedirectToAction("GridViewPartial");
        }

What i want is if i can get value of successid in ajax retrun along with gridview partial html ... so that i can display message according to that..

Aritra B
  • 1,726
  • 6
  • 29
  • 45
Mahajan344
  • 2,492
  • 6
  • 39
  • 90

2 Answers2

5

If the operation fails, simply return that as a JSON result:

public ActionResult AddUsers(Usertable model)
{
    int successid = ManageUserExecutor.Save(model);
    if (successid == -1)
    {
        List<usp_GetListOfUsers_Result> objList = new List<usp_GetListOfUsers_Result>();
        return PartialView("GridViewPartial", objList);
    }
    else
    {
        return Json(new { id = successid });
    }
}

and your AJAX call:

function AddUser() {
    showProgress();
    $.ajax({
        url: 'ManageUsers/AddUsers', // <!-- TODO: This url should NOT be hardcoded like that. It should be generated by a server side helper
        cache: false, // <!-- That's what should be used instead of reinventing wheels with Math.random stuff
        data: $("#frmManageUsers").serialize(),
        type: 'POST',
        success: function (data) {
            if (data.id) {
                // the controller action returned a JSON result with id property =>
                // handle it here
                alert('Sorry, an error occurred, successid: ' + data.id);
            } else {
                // The operation succeeded and the controller action returned a partial
                // view => update your DOM here
                $("#grid").html(data);
            }
        }),
        error: function (request, status, error) { ShowErrorMessage(); },
        complete: function () { hideProgress(); ShowSuccessMessage(); }
    });
}  

Also notice that I have gotten rid of the datatype: 'json', parameter present in your request. This is wrong in 2 ways:

  1. The correct property is called dataType instead of datatype
  2. Since the controller action could return HTML or JSON (depending on whether the operation succeeds), we leave to jQuery to use the Content-Type response HTTP header set by the web server to automatically deduce the correct type and parse the data variable passed to your success callback.
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Sir..Thanks you so much for quick and accurate answer.. and also for your advise on cache and url ...As you mentioned that url shouldn't be hardcoded..It should be generated by a server side helper.... what do u mean by that.. and how can achieve that..could you please help me out with this..with some example etc...Thanks once again for your help – Mahajan344 Nov 23 '13 at 16:26
  • I mean that you should be using the `Url.Action` helper on some of your DOM elements attributes that you could access in the `AddUser` action. – Darin Dimitrov Nov 23 '13 at 16:37
0
public ActionResult AddUsers(Usertable model)
{
    var viewModel = new ReturnValue();

    int successid = ManageUserExecutor.Save(model);
    if (successid == -1)
    {
        viewModel.Message= "Failed"; 
        viewModel.ViewString = this.RenderViewToString("GridViewPartial", objList);
    }
    else
    {
        viewModel.Message= "Success";
        viewModel.ViewString = this.RenderViewToString("GridViewPartial");
    }
}

And use data.ViewString to access rendered partial view html.

$("#grid").html(data.ViewString);

And use data.Message for accessing the message you want.

$("#grid").html(data.Message);

You can find RenderViewToString function here.

Community
  • 1
  • 1
emre nevayeshirazi
  • 18,983
  • 12
  • 64
  • 81