2

I have a page called Bookprogram which contains 6 input controls namely, txtName, txtEmail, txtPhone, selectcat[dropdown for categories], txtDate, txtMessage. Now when am done with all the validations for the above control, I want to store the data in db. I know how to perform both in ajax as well as complete page posting.

If it's in ajax, after validations, I would just call $.ajax and post the data as a string and fetch it in controller as below:

[HttpPost]
public JsonResult BookProgram(string name, string email, string phone, string category, string date, string message)
{
       //code to save into db
       return Json(result);
}

If I have to post a whole page, after validations I would just do a $(form).submit(); and write as below in controller:

[HttpPost] 
public ActionResult Bookprogram(Mymodel model)
{
     //Code to save the data 
     return View();
}

I just want to know which is better, safe and good to use as I have to display a message after successful submission. I know I can take either of the ways to display message but Is postback[page refresh] really needed in this scenario and if yes what are the advantages of it over ajax post?

EDIT :

I just went through this link and tried to implement 2nd solution of highest voted answer but for my bad luck it wasn't hitting the controller itself. I have kept breakpoint in my controller.

$(form).on("submit", function (e) {
        e.preventDefault();
        ValidateForm(form);
        var selectedVal = $(form).find('select').children(":selected").val();
        if(selectedVal=="")
        {
            $(form).find('div.bootstrap-select').children(":first").addClass('alert-danger');
            $(form).find('div.bootstrap-select').next('.text-danger').html('Please select a category!');
        }
        var formContainer = $(form + ' .text-danger');
        if ($(formContainer).text().length == 0) {
            $.ajax({
                url: '/Home/BookProgram/',
                type: "POST",
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: $('#fbookprogram').serializeArray(),
                success: function (data) {
                    if (data.result == "Success") {
                          alert('success');
                    }
                    else {
                         alert('fail');
                        return false;
                    }
                    return true;
                }
            });
        }
        $(form).unbind('submit');
        return false;
    });

Controller :

public ActionResult BookProgram(MyModel model)
{
    if(ModelState.IsValid)
    {
        //code to save data
    }
    return Json(new { success = false });
}

What is that I am missing here.

Community
  • 1
  • 1
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
  • 1
    You can still use `public ActionResult Bookprogram(Mymodel model)` for the ajax post (and you should because you can take advantage of model binding and checking `ModelState.IsValid`) –  Feb 09 '15 at 09:04
  • @StephenMuecke Ok that's cool. Is there any difference in safety and time consumption for posting the data? – Guruprasad J Rao Feb 09 '15 at 09:39
  • 1
    Which way you do it really depends on what you do after you save the data. If all you doing is displaying a message, I would just do a normal submit. If the model has errors you can return the view (taking advantage of `ModelState` errors and the `ValidationMessageFor()` to display them). If the data is saved OK, then redirect to another view (say an Index or Details view where you can display a success message (using `TempData`). If however you want to return to the view to perform other actions on the page then ajax might be better. –  Feb 09 '15 at 09:47
  • 1
    Based on you first code snippet,I suspect you must be manually building the values to postback - you can just use `$.post(url, $('form').serialize(), function(data) { // do something ...` –  Feb 09 '15 at 09:50
  • that's nice explaination @StephenMuecke.. Thanks for that.. – Guruprasad J Rao Feb 09 '15 at 09:55

2 Answers2

2

Post Back

  1. Browser Handling - The only advantage I can think of is that the browser will handle redirects and progress loading for you. You don't need to write the logic to redirect users or show a loading bar.

AJAX

  1. Asynsconous - With AJAX you're getting asyncronous calls so the browsers thread isn't blocked. This allows the user to still interact with the UI whilst waiting for the response from your request.

  2. Better Performance -You generally don't need to reload the entire page resulting in less overhead & HTTP requests being made.

FYI - You can still model bind with JsonResult

public JsonResult BookProgram(Mymodel model)
{
       //code to save into db
       return Json(result);
}
heymega
  • 9,215
  • 8
  • 42
  • 61
  • Well bit cleared now!! do have anything to say regarding data security in both the scenarios!! – Guruprasad J Rao Feb 09 '15 at 09:51
  • 2
    AJAX and Post Back both ultimately create HTTP requests so you can't regard one method as being less safe than the other. – heymega Feb 09 '15 at 10:16
  • @heymaga... Can you please let me know how to bind model with JsonResult?? – Guruprasad J Rao Feb 09 '15 at 17:19
  • The request data is bound to the model exactly the same way with the ActionResult. Remember JsonResult & ActionResult are just return types of your method. The fact that you're using a controller allows you (by default) to use the default model binder. So you can model bind any public method within a controller – heymega Feb 09 '15 at 17:28
  • @heymaga.. What I just tried now is after validations I just called my Controller Jsonresult method through ajax and I tried to get the model as parameter in that method as you specified in your answer. But the model was just coming null. Can you please elaborate on this, with example if possible.. – Guruprasad J Rao Feb 09 '15 at 17:56
  • @Kaushik Add you Ajax code to your original post and I'll check it out :) – heymega Feb 09 '15 at 19:04
  • @heymaga.. I have edited my question. Please check it out... :) – Guruprasad J Rao Feb 09 '15 at 19:40
  • @heymaga.. I have found the solution. Thanks for the suggestion.. :) – Guruprasad J Rao Feb 09 '15 at 20:09
1

Post back - is a classic workflow. Delegate most of inner work to your webbrowser. All your responce logic calculated on server side.

AJAX - is a modern way of building dynamic web-applications. Base approach for single-page-applications. Most of work in this case should be done on client side.

aleha_84
  • 8,309
  • 2
  • 38
  • 46