1

This is kind of an odd question but I could use some direction

I been working on a project using MVC and everywhere I look at examples, that the examples I see are nothing like I am really doing.

All examples are using Razor syntax and using @model to pass models from the controller to the view. But I am doing something different than what I am seeing and am wondering if I am using MVC incorrectly.

Instead of using Razor and @model, I am using HTML and JQuery and javascript objects and getting returned data that way.

So I am confused, am I doing things the "right way" or am I doing it the "wrong way"?

EDIT: How I get Data

// Get ClientInfo
function GetClientInformation() {
    $.ajax({
        type: "GET",
        url: AddClientURLParam.AddGetClientInformationURL,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data, textStatus, jqXHR) {
            ClientDataToGet(data);
        }
    })
}
function ClientDataToGet(clientInfoData) {
    $("#txtCompanyName").val(clientInfoData.CompanyName);
    $("#txtAddress1").val(clientInfoData.Address);
    $("#txtAddress2").val(clientInfoData.Address2);
    $("#txtCity").val(clientInfoData.City);
    $("#txtState").val(clientInfoData.State);
    $("#txtZip").val(clientInfoData.ZipPostal);
    $("#txtEmail").val(clientInfoData.Email);
    $("#txtContact").val(clientInfoData.Contact);
    $("#txtPhone").val(clientInfoData.Phone);
    $("#txtWorkPhone").val(clientInfoData.WorkPhone);
    $("#txtMobile").val(clientInfoData.Mobile);
    $("#txtFax").val(clientInfoData.Fax);
    $("#txtOther").val(clientInfoData.OtherPhone);
}
Chris
  • 2,953
  • 10
  • 48
  • 118

3 Answers3

1

JavaScript/JQuery has a different purpose than Razor. Razor generates pages on the server, and once it's received by the client, Razor is finished.

It's a little extra overhead to use JSON, and not the traditional way of doing a website, but it might be best in some cases. If you are just calling JSON once, then it would probably be better just to let Razor do the generating, and use JavaScript for things that need to change on the client side.

You can use a JSON string as the model so you don't have to hit the server the first time:

@model string
<!-- ... -->
<script>
var model = @Html.Raw(Model); // Raw JSON
</script>

Razor Example

In your changes above, you showed a JavaScript way of doing this. If you're doing lots of JavaScript, I could see the benefit of just doing all of your generating in the client (you might look at something like handlebars). However, in my opinion, the razor code is easier to read.

<form>
  <div>
    @Html.LabelFor(m => m.CompanyName)
    @Html.TextBoxFor(m => m.CompanyName)
  </div>
  <!-- etc -->
</form>

Where as you were already generating a label and a textbox in code elsewhere.

It can handle most input validation for you, both on the client and the server (in case the JavaScript doesn't work), so that's less code you have to create yourself:

public class MyModel {
  [Required, StringLength(50)]
  public string Title {get;set;}
}

I think it would be worth the time to learn how to develop multiple ways so that you can use the best solution for the project.

bradlis7
  • 3,375
  • 3
  • 26
  • 34
  • Well I am using JQuery and Ajax to get data from the server. Like I have a Customer form and when I add a new customer I use JQuery and Ajax to send the data to my controller and when I update a customer I'll do the same thing use jQuery Ajax to call the method from my control, then use the returned data to populate my textfields and when I update same thing, use JQuery and Ajax to pass the data over to my controller – Chris Sep 16 '15 at 22:51
  • @Chris how about viewing the data? Are you querying the data and then using JavaScript to display it? In a recent project of mine, I used JSON to get the data into a JavaScript variable so I can paginate on the client side without having to refresh for more data. Editing an entry used the traditional approach, in that Razor generated the form, and it was submitted like a normal POST request. There's about 100 different ways to make a web app, and you're not necessarily wrong, but it's nice to know what options are available to know the best tool for each situation. – bradlis7 Sep 17 '15 at 14:19
  • I just made an edit to show I am getting data and passing it – Chris Sep 17 '15 at 14:54
  • @bradlis7 I'm not sure I entirely agree with your statement about server side rendering being the traditional way of doing web development (nor AJAX introducing overhead). AJAX has been around for a long time. AJAX can also make requests asynchronously while the pages loads giving a might higher perceived performance gain as opposed to the heavy single-threaded server-side rendering with the Microsoft tools. – Jordan Parmer Sep 17 '15 at 15:05
  • Thanks for the edit, hows does BootStrap work if you are using Razor? does it still work as it would with applying the classes to HTML? one thing that I did notice in your example is that you are using a form tag, I haven't used that tag because from what I seen causes a sort of postback, or am I wrong? – Chris Sep 17 '15 at 15:47
  • AJAX wasn't popular for a long time, so that's why I consider it not modern. Also, in a lot of cases, the server has more resources than the client (it might be a phone), so the single thread can do more work than a client, and some browsers didn't have async until recently. – bradlis7 Sep 17 '15 at 15:50
  • 1
    You can add html attributes through passing an anonymous object: `@Html.TextBoxFor(m => m.Title, new { @class = "form-control" })`. You can catch the submission using JavaScript so that it won't submit (http://stackoverflow.com/a/6960586/179311). – bradlis7 Sep 17 '15 at 16:01
  • @bradlis7 I'm sorry but that just isn't true. JQuery, HTTP GET requests, etc. have been asynchronous for a VERY LONG time. Saying a browser hasn't supported async until recently is false. Asynchronous web programming can pull down smaller chunks at a time whereas server rendering has a large payload that must come down all at once. – Jordan Parmer Sep 17 '15 at 16:09
  • I guess you are right in that it downloads more than one file at a time. I was thinking about the ` – bradlis7 Sep 17 '15 at 16:21
1

What's "the wrong way"?

The .cshtml files are a "seam". They combine elements of C# and HTML.

@model is a global variable somewhat similar to AngularJS $scope. The idea is that you'll use that model for each view and then validate its contents and perform server-side operations after it is manipulated by the client.

Depending on the application, you might not want to do that. It's perfectly plausible to use JavaScript XHR requests against the underlying ASP.NET API to get data returned. I'm reasonably certain that's what ASP.NET MVC is doing behind the scenes anyway. It seems like what you're saying is that you're just hand-rolling it.

Whether or not this is valid really depends on you. Is it painful? Is it testable? Do you feel confident in the code?

Depending on what you are trying to do it might be time to check out one of the client-side JavaScript MVC libraries (I mentioned one, there are others) and just use ASP.NET Web API to communicate with the server.

Hope that helps.

Chaim Eliyah
  • 2,743
  • 4
  • 24
  • 37
  • What do you mean by "hand rolling it"? I don't find it painful at all and I am confident in how I am doing it but when I look at examples or flip through a tutorial I always get the feeling that I am not doing things correctly. Because everything is using Razor and I am not, in my views you would be hard pressed to find @model anywhere in the views – Chris Sep 16 '15 at 22:48
  • By "hand-rolling", I mean you are doing what Razor does for you by using JavaScript to explicitly make client requests. If it's not painful, you're probably doing a fine job of it. If it's not *testable*, you will run into problems at some point. – Chaim Eliyah Sep 16 '15 at 22:50
  • I don't find it painful because I don't know how to do it any other way, I guess you could say I am used to doing it this way because I started off with MVC this way. Without really much direction with it. I have added a test project to the web application but have yet to use it – Chris Sep 16 '15 at 22:54
  • 1
    I'd try different things. Make a .cshtml page that uses Backbone or Angular and see if you like that. Make one that just uses @model and make yourself conform to the ASP.NET MVC spec. See which feels more comfortable. Either way, testability is the key. If you're writing your own REST application in JavaScript without any way to test, down that path lies the aforementioned pain. – Chaim Eliyah Sep 16 '15 at 22:58
  • 1
    I'm going to give that a try, I think that's where I worry about is not conforming to the MVC spec. I like whatever won't cause a postback – Chris Sep 16 '15 at 23:00
  • 1
    Good luck with your experiments! --Re: POST, that's something you have to worry about with WebForms more than ASP.NET MVC. Form submission is relatively straightforward with ASP.NET MVC. – Chaim Eliyah Sep 16 '15 at 23:01
1

The key difference is that the razor syntax is used to generate page content on the server at load time (using Microsoft's MVC framework) whereas the AJAX pattern you are using makes web service calls after the page has hit the client.

Outside of the Microsoft eco-system, you'll see a lot more AJAX. Web purists are going to prefer AJAX over server-side rendering - especially when using client frameworks like AngularJS.

There are pro's and con's to each approach.

Client with AJAX

A purist sticks with just AJAX calls and dynamically loads pieces of the page. Using server rendering is expensive. You'll notice a considerable delay (sometimes measured in seconds) when rendering the page on the server.

With AJAX, the page can start rendering on the client while loading other data from the server. It's asynchronous and can run in parallel. This gives a better perceived performance. With server rendering, the page has to be fully rendered on the server prior to the user seeing any client-side rendering.

Server Rendering

The benefit of rendering on the server is that you can use the Razor view template code to generate a lot of your HTML that you would otherwise have to do on the client. You'll get the added benefit of Microsoft's API's and some of the fancy syntax for embedding logic into your HTML which might be useful if you aren't using a client framework like AngularJS.

Using server rendering does not completely eliminate the need to make AJAX calls and doesn't prevent post-backs.

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
  • I like this explanation, I worked alot with WebForms and always having postbacks and didn't really like it so much becuase it didn't look seamless. I quite enjoy the fact that I don't have to deal with postbacks, but I always felt I wasn't doing it correctly with MVC because everywhere you look everyone uses Razor in their examples, even tutorials. But now with your pros and cons, to me it looks like I am achieving the direction I wanted to go, whether it conforms with specs or not. Sometimes it gets difficult trying to find examples the way I am doing things. – Chris Sep 17 '15 at 15:36
  • As for frameworks like AngularJS, there were so many out there to choose from that I didn't know which direction to go with, so I decided to actually learn to work with JQuery and JavaScript so I wasn't dependent on other frameworks. At some point in time I will eventually learn AngularJS or BackBone or KnockOut, but it brings up the question, do I really need to because I am using JQuery and JavaScript already? I know using those frameworks would make things faster, but it isn't using those frameworks without a foundation like driving a car without knowing why it works? – Chris Sep 17 '15 at 15:40
  • @Chris Excellent question. Those frameworks are a pretty big step forward. Changes the entire structure of how you do web programming. It's kind of like comparing raw C (JS/JQuery) to .NET (Angular/Backbone). AngularJS is an entire framework whereas JQuery is more of a convenience library to assist JavaScript + DOM. JQuery is MUCH better than doing raw JavaScript + DOM. However, you'll still find yourself doing a lot of boilerplate code that a more advanced framework will take care of for you. However, getting into AngularJS is a big undertaking as it isn't trivial. – Jordan Parmer Sep 17 '15 at 15:47
  • 1
    I'd say your choice of JQuery over Razor is a good move (by the sounds of what you are trying to accomplish). If you are going to go deep in the web world, start taking a look at Backbone or Angular. – Jordan Parmer Sep 17 '15 at 15:49
  • I had once started looking at Angular, it is a big undertaking. I always thought that if I started off with Angular (or any other client side framework) that I would be missing out on some finer points and other intricacies of development – Chris Sep 17 '15 at 15:53
  • Yes, that's a good point. If you are coming into the web world, it is better to get the fundamentals first because Angular incorporates a lot of abstraction. JQuery is a good starting point. Angular encompasses the entire way you do web development so it is much more invasive (and a steep learning curve to boot). – Jordan Parmer Sep 17 '15 at 16:11
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89935/discussion-between-chris-and-jordan-parmer). – Chris Sep 17 '15 at 16:12