European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

European ASP.NET MVC 5 Hosting - UK :: How to Use jQuery DatePicker for MVC

clock December 11, 2014 08:38 by author Scott

For those of you using ASP.NET MVC and hoping to receive a little guidance on how to implement a jQuery UI DatePicker widget on a date input field, as well as the appropriate way to pass dates from the view back to the controller,  the following article is just for you.

The first gotcha was to download the entire jQuery UI (Combined Library) package from Nuget.  Downloading the older jQuery UI DatePicker package has some incompatibilities with the jQuery core framework that the bootstrap template needs to function correctly.

The next step is to extend the model you are using to support a datetime field you’d like to manage with the jQuery UI DatePicker. Take a look at the DateOfBirth field in the code below.

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; } 

    [Required]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; } 

    [Required]
    [Display(Name = "Date of Birth")]
    public DateTime DateOfBirth { get; set; }

Extending the view to support this datetime field is pretty straight forward razor coding. The one thing to notice in this piece of code is the “datefield” css class used in the TextBoxFor method. We’ll be using the class later on to allow for easier jQuery UI DatePicker widget initialization. It also allows for more reusability across your applications.

<div class="form-group">
    @Html.LabelFor(m => m.DateOfBirth, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.TextBoxFor(m => m.DateOfBirth, new { @class = "form-control datefield" })
    </div>
</div>

The code to initialize any jQuery UI DatePicker widgets is only 3 lines of code. We utilize the “datefield” css class here as a generic selector so all input fields with this class will transform into jQuery UI DatePicker widgets.

$(function () {
    $(".datefield").datepicker();
});

The final touch is to include all required .js and .css files necessary to a common layout which provides this codes use throughout your web application.  If you are concerned about page load times you can cherry pick where you’d like these includes to go.

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

        </footer>
    </div> 

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap") 

    <link href="~/Content/themes/base/jquery.ui.core.css" rel="stylesheet" />
    <link href="~/Content/themes/base/jquery.ui.datepicker.css" rel="stylesheet" />
    <link href="~/Content/themes/base/jquery.ui.theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-ui-1.10.4.js"></script>
    <script src="~/Scripts/Common/DatePickerReady.js"></script> 

    @RenderSection("scripts", required: false)
</body>
</html>

The nice thing about this approach is that ASP.NET MVC5 takes care of all the model binding for you since the jQuery UI DateTime picker sets the input field as a valid date value that native model binding understands. By the time you get to your controller you’ll have your datetime value set.

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            var message = new EmailMessage();
            message.ToEmail = model.EmailAddress;
            message.Subject = "Insurance Website Registration";
            message.IsHtml = false;
            message.Body =
                String.Format("You have succesfully registered for Vanderbuilt Insurance with the following" +
                              "username: {0}", model.UserName); 

            var status = EmailService.SendEmailMessage(message); 

            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    } 

    // If we got this far, something failed, redisplay form
    return View(model);
}



European ASP.NET MVC 5 Hosting - UK :: Tips Improving Your ASP.NET MVC Codebase

clock October 27, 2014 10:05 by author Scott

Some of you sometimes think why your application eat up until 1 GB-2GB memory on production server. After looking through the code, doing some profiling, maybe shaking your head a bit, you've figured out what the issue is and now you need to give some feedback.

In this tutorial, I will show some tips that you can follow to reduce your memory usage on production server and keep your ASP.NET MVC codebase working as you’d expect.

1. Understand the queries in your problem domain

The root cause of the support ticket I received was a simple case of fetching too much data from the database, causing obscene amounts of memory usage.

It's a common enough issue. You're building a simple blog, it has posts and it has media (images, videos, attachments). You put a Media array onto your Post domain object. Your Media domain object has all the image data stored in a byte array. Since you're using an ORM, there's a certain way you need to design your domain model to play nice; we've all experienced this.

public class BlogPost {
    public ICollection<BlogMedia> Media { get; set; }
}
public class BlogMedia {
    public byte[] Data { get; set; }
    public string Name { get; set; }
}

There's nothing absolutely wrong with this design. You've modeled your domain accurately. The problem is, when you issue a query through your favorite ORM, it eagerly loads all the data associated with your blog post:

public IList<BlogPost> GetNewestPosts(int take) {
    return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).ToList();
}

A seemingly innocuous line (unless you've been bitten), a sneaky monster is lying in wait with big consequences if you haven't disabled lazy loading or didn't tell your ORM to ignore that big Data property on blog media.

It's important to understand how your ORM queries and maps objects and make sure you only query what you need (for example using projection).

public IList<PostSummary> GetNewestPosts(int take) {
    return _db.BlogPosts.OrderByDescending(p => p.PostDate).Take(take).Select(p => new PostSummary() {
        Title = p.Title,
        Id = p.Id
    }).ToList();
}

This ensures we only grab the amount of data we really need for the task.

It's OK to have more than 5 methods on a repository; be as granular as you need to be for your UI.

2. Don't call your repositories from your views

Consider this line in an MVC view:

@foreach(var post in Model.RelatedPosts) {
    ...
}

It seems innocent enough. But if we take a look at what exactly that model property is hiding:

public class MyViewModel {

    public IList<BlogPost> RelatedPosts {
        get { return new BlogRepository().GetRelatedPosts(this.Tags); }
    }

}

Your "view model" has business logic in it on top of calling a data access method directly. Now you've introduced data access code somewhere it doesn't belong and hidden it inside a property. Move that into the controller so you can wrangle it in and populate the view model conciously.

This is a good opportunity to point out that implementing proper unit tests would uncover issues like this; because you definitely can't intercept calls to something like that and then you'd realize injecting a repository into a view model is probably not something you want to be doing.

3. Use partials and child actions to your advantage

If you need to perform business logic in a view, that should be a sign you need to revisit your view model and logic. I don't think it's advisable to do this in your MVC Razor view:

@{
    var blogController = new BlogController();
}

<ul>
@foreach(var tag in blogController.GetTagsForPost(p.Id)) {
    <li>@tag.Name</li>
}
</ul>

Putting business logic in the view is a no-no, but on top of that you're creating acontroller! Move that into your action method and use that view model you made for what it's intended for. You can also move that logic into a separate action method that only gets called inside views so you can cache it separately if needed.

//In the controller:

[ChildActionOnly]
[OutputCache(Duration=2000)]
public ActionResult TagsForPost(int postId) {
    return View();
}

//In the view:

@{Html.RenderAction("TagsForPost", new { postId = p.Id });}

Notice the ChildActionOnly attribute. From MSDN:

Any method that is marked with ChildActionOnlyAttribute can be called only with the Action or RenderAction HTML extension methods.

This means people can't see your child action by manipulating the URL (if you're using the default route).

Partial views and child actions are useful tools in the MVC arsenal; use them to your advantage!

4. Cache what matters

Given the code smells above, what do you think will happen if you only cached your view model?

public ActionResult Index() {
    var homepageViewModel = HttpContext.Current.Cache["homepageModel"] as HomepageViewModel;

    if (homepageViewModel == null) {
        homepageViewModel = new HomepageViewModel();
        homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);

        HttpContext.Current.Cache.Add("homepageModel", homepageViewModel, ...);

    }

    return View(homepageViewModel);
}

Nothing! There will not be any performance gain because you're accessing the data layer through a controller variable in the view and through a property in the view model... caching the view model won't help anything.

Instead, consider caching the output of the MVC action instead:

[OutputCache(Duration=2000)]
public ActionResult Index() {
    var homepageViewModel = new HomepageViewModel();

    homepageViewModel.RecentPosts = _blogRepository.GetNewestPosts(5);

    return View(homepageViewModel);
}

Notice the handy OutputCache attribute. MVC supports ASP.NET Output Caching; use it to your advantage when it applies. If you are going to cache the model, your model needs to essentially be a POCO with automatic (and read-only) properties... not something that calls other repository methods.

Conclusion

I hope with tutorial above, it will help you to minimize your memory usage on the server.

 



European ASP.NET MVC 5 Hosting - UK :: ASP.NET MVC 5 Scaffolding

clock October 13, 2014 07:28 by author Scott

In this article, I will show you how to use Scaffolding With your ASP.net MVC 5 Application. I assume that you all know about scaffolding and I don’t need to explain it again. In our previous post, we have also explained about Scaffolding with the Repository Pattern in ASP.NET MVC 3.

In this article, we will be more focus in adding scaffolded item to ASP.net MVC 5.

1. Let's create an ASP.net MVC 5 web application in Visual Studio 2013 and name it as ScaffoldingMVC5.

2. Right click your Controllers folder and Add New Scaffolded Item is as below.

3. From the Add Scaffold window, select the MVC 5 Controller with views,using Entity Framework scaffold template.

4. Add a controller. Please see the below screenshot

Then, please fill a name for your Data context as below, for example DataContext

5. You have done great job and this is the result

Testing the Result

Index Page

Create Page

Details Page

Edit Page

Delete Page

All above CRUD operations were generated according to our Model class Pet.

Pet.cs

Key points of the above code

  • [ScaffoldColumn(false)] means,the property which it declared will not use for scaffolding.In other words, that property will not be shown on the UI (i.e. Created property will not be shown).
  • Data validations of the form elements are happening ,according to the above model's Data Annotation values.
  • Let's explore it.

If you click the Create button, without entering anything.What will happen ?

What if you try to enter a wrong data type ?

 


Calender has been shown, if it's a DateTime property.

Great, right?



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in