0

During ASP.Net development i am often unsure weather i should be performing some functionality using an ajax request vs handling it all on the client with JavaScript. I often will want to use Jquery ajax functions in order to speed development up and improve maintainability even though i can achieve the same result without contacting the server.

Here is one example. In my MVC view i need to update a partial view in response to a button click. Here is a simplified version of my partial view

  @foreach (Requestbox.Code.XmlContentField xmlControl in Model.RequestContentControls)
    {
        if (Model.IsInEditMode)
        {
          ViewContext.Writer.Write("<div class='editDiv'>
          <a href='#' onclick='EditClick()'>Edit</a>
          <a href='#' onclick='DeleteClick()'>Delete</a>");             
        }

        switch (xmlControl.ControlType)
        {            
            case "TextBoxField":
              <div class="clearfix">
                  @Html.DevExpress().Label(settings => { 
                 settings.Name = xmlControl.FieldName + "Label";
                 settings.AssociatedControlName = xmlControl.FieldName + "TextBox";
                 settings.Text = xmlControl.LabelText;

             }).GetHtml()
                  <div class="input">
                      @Html.DevExpress().TextBox(settings => {
                     settings.Name = xmlControl.FieldName + "TextBox";
                     MvcExtensionHelpers.SetTextBoxSettings(settings);
                     settings.ControlStyle.CssClass += " full-width";
                 }).GetHtml()
                  </div>
              </div>

                break;
            case "Header":
                string header = string.Format("<{0}>{1}</{0}>",                                     xmlControl.HeaderType,xmlControl.Value);
                @Html.Raw(header)
                break;
        }

        if (Model.IsInEditMode)
        {
            ViewContext.Writer.Write("</div>");
        }
      }

When the Edit button is clicked i need to wrap each of my sections in a div and add 2 anchor elements with onclick functions inside. I can do this by using an ajax post request and setting the Model with "IsInEditMode to true" here is the code i could call, which replaces the current partial view with the new one.

function EnableEditClick() {
$.post(rootDir + "Admin/EditClick",null,
function(partialViewResult){ 
  $("#refTable").html(partialViewResult);
 });
}

Here is the Action that could handle the ajax request

public ActionResult EditClick()
{
MyModel model = new MyModel();
model.IsInEditMode = true;

return PartialView("CustomRequest", model);
}

This is one solution, another would be to handle this all on the client by using jquery to select each of my elements that are needed and to insert the anchor elements directly. I would also be able to take some code out of the view. So something like this (Haven't tested this code but i hope you get the idea)

function EditClick()
   {
      var elements = $('.myTable .clearfix')
      elemtns.append(' <a href='#' onclick='EditClick()'>Edit</a>
          <a href='#' onclick='DeleteClick()'>Delete</a>');
}

I am torn on which will be better maintainability wise, as with the ajax way i don't have to write html in JavaScript pages and i think it will be clearer and more readable when revisting the code. However i am then using a unnecessary request to the server when i could it handle all on the client.

So my questions is should i always be doing everything on the client if possible even at the result of maintainability. Any feedback on my example is much appreciated as well.

user2945722
  • 1,293
  • 1
  • 16
  • 35

2 Answers2

1

I recommend you to use AJAX for operations, which require some background calculations on the server or to retrieve some DB data from the server. For GUI generation I would use JS, as it is quite quick, thanks to V8.

If you need to generate GUI by embedding some server data into it and this page has complex layout, I would use server side template engine.

GuardianX
  • 515
  • 11
  • 29
0

In the example you've given, I would recommend the JS approach to control the availability of the edit and delete buttons. Or possibly a combination of the two.

When you make an Ajax call it creates a background request that causes some HTTP traffic. Unless there's some processing needed on the server to fulfil the request, then there is not much use sending that request to the server.

From looking at your code then the action you want to perform is to add two anchors to the page. This can be done easily with JS. You could even combine the two by including a partial view on your page that contains the elements you wish to include, wrapped in some markup to hide them.

You could create a partial view with the button markup.

<a href='#' onclick='EditClick()'>Edit</a>
<a href='#' onclick='DeleteClick()'>Delete</a>

And then include in your view.

<div id="buttons" style="display: none;">
    @Html.Partial("_ButtonView")
</div>

Your JS would become.

function EditClick()
{
    $("#buttons").toggle("display");
}

Check this JSFiddle for an example of what I mean.

In the context of this question, I would consider using an Ajax request for the actual edit action that returns a Json result with the action output. This would end up with something like.

$.ajax({ // ajax call starts
    url: "YourArea/YourController/EditClick",
    data: {"your data"},
    dataType: 'json',
    success: function(data) {
        //handle json response
      }
  });

This Ajax request would call the controller code.

public JsonResult EditClick()
{
    var myResult = Helper.Edit();

    return Json(new { result = myResult });
}

Conclusion: If an event/action only affects what the user can see on the UI (i.e. controlling visibility and initiating animations) then you would probably only want to use JS/jQuery. If there's something more happening like server processing or fetching data from DB required then consider using Ajax.

In your example it seemed like the choice was between adding the elements dynamically to the page with JS or executing an Controller method via Ajax to get the elements as a partial view. I hope this answer provides a good solution for you.

Robin French
  • 675
  • 6
  • 17