13/09/2015

Lazy loading partial view in MVC C#

Đối với trang web có nhiều phần nội dung khác nhau, 

ví dụ: 

1) header 

2) body

2.1) left

2.2) center

2.3) right

3) footer

 Để tăng thời gian hiển thị nội dung trang web lên giao diện cho thân thiên với người dùng thay vì load 1 lần ta có thể thực hiện load từng phần riêng lẻ với partial view

Đoạn code sau thể hiện load footer

1) Trên view layout

<script>

    $(document).ready(function() {

//dùng jquery thực hiện load action FooterContents trong controller Home

//vào div có id là partialFooter

        $("#partialFooter").load('@Url.Action("FooterContents", "Home")');

    });

</script>

2) Trong code behind controller Home, action FooterContents

public async Task<ActionResult> FooterContents()
{
List<ObjectDTO> objDTOs = new List<ObjectDTO>();

try
{
//uow call bll to get data from database
objDTOs = await unitOfWork.Entity.GetList(20);
//do some things..
}
catch(Exception ex)
{
//handle exception
}
//display listing
return PartialView("FooterContents", objDTOs);
}

09/10/2014

Custom valid MVC C# field

 Trong MVC, ngoài những ValidationAttribute có sẵn như Required, Display ..

Đôi khi bạn cần gọi hàm check riêng của bạn cho 1 field name nào đó

ví dụ class:

public class AccountDTO

{

/// <summary>

/// Tên đăng nhập

/// </summary>

[Required(ErrorMessage = "Nhập tên đăng nhập")]

[Display(Name = "Tên đăng nhập")]

[CheckUsernameAvailable]

public string Username { get; set; }

//những field khác ....

}

Hãy lưu ý: CheckUsernameAvailable 

cần kiểm tra username có ai sử dụng hay chưa

Ta có class tương ứng


public class CheckUsernameAvailable : ValidationAttribute

{

public CheckUsernameAvailable()

: base("")

{

}


protected override ValidationResult IsValid(object value, ValidationContext validationContext)

{

if (value != null)

{

//parse object qua string

string userName = Convert.ToString(value);

//thực hiện query database

//DAO execute here

var result = checkUsernameAvailable(userName);

if (!result)

{

//khai báo errorMsg

errorMsg = string.Format("Tên đăng nhập {0} đã có người sử dụng", userName);

return new ValidationResult(errorMsg);

}

}

return ValidationResult.Success;

}
}

09/10/2013

Sql management studio

Anh em làm dev với cơ sở dữ liệu sql server chắc không ai không cần dùng SSMS đâu nhỉ

Tất nhiên miễn phí và chất lượng, hàng của MS mà ;)

link thông tin SSMS: https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms

link download bản mới nhất: https://aka.ms/ssmsfullsetup

12/03/2012

Công cụ điều khiển máy tính từ xa


Đôi khi bạn cần hỗ trợ "ai đó" từ xa, có thể bạn sẽ cần: 

Bạn có thể dùng TeamViewer

website: https://www.teamviewer.com

TeamViewer được tối ưu để sử dụng ít băng thông và tạo kết xuất ảnh hiệu quả hơn, do đó dự kiến sẽ cho chất lượng ảnh được cải thiện theo băng thông được cung cấp. Các lợi ích khác bao gồm truyền tập tin nhanh hơn lên đến 15 lần và mức sử dụng dữ liệu thấp hơn đến 30%. Download team viewer

lựa chọn tiếp theo không kém "chất" là UltraViewer

website: https://ultraviewer.net/ 

với hơn 40 triệu lượt tải, 100% miễn phí và rất dễ sử dụng ;)

hope this help :)

20/06/2011

CTY mới

 Mai đi làm ngày đầu tiên ở cty mới sau 3 năm cày cuốc freelance và mở cty chưa đủ tài ...

Lại làm thuê kiếm bia uống...

15/06/2011

Paging - pager helper class c#

//định nghĩa class chia trang thường dùng

 public class Pager

    {

        public Pager(

            int totalItems,

            int currentPage = 1,

            int pageSize = 10,

            int maxPages = 10)

        {

            // calculate total pages

            var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);


            // ensure current page isn't out of range

            if (currentPage < 1)

            {

                currentPage = 1;

            }

            else if (currentPage > totalPages)

            {

                currentPage = totalPages;

            }


            int startPage, endPage;

            if (totalPages <= maxPages)

            {

                // total pages less than max so show all pages

                startPage = 1;

                endPage = totalPages;

            }

            else

            {

                // total pages more than max so calculate start and end pages

                var maxPagesBeforeCurrentPage = (int)Math.Floor((decimal)maxPages / (decimal)2);

                var maxPagesAfterCurrentPage = (int)Math.Ceiling((decimal)maxPages / (decimal)2) - 1;

                if (currentPage <= maxPagesBeforeCurrentPage)

                {

                    // current page near the start

                    startPage = 1;

                    endPage = maxPages;

                }

                else if (currentPage + maxPagesAfterCurrentPage >= totalPages)

                {

                    // current page near the end

                    startPage = totalPages - maxPages + 1;

                    endPage = totalPages;

                }

                else

                {

                    // current page somewhere in the middle

                    startPage = currentPage - maxPagesBeforeCurrentPage;

                    endPage = currentPage + maxPagesAfterCurrentPage;

                }

            }


            // calculate start and end item indexes

            var startIndex = (currentPage - 1) * pageSize;

            var endIndex = Math.Min(startIndex + pageSize - 1, totalItems - 1);


            // create an array of pages that can be looped over

            var pages = Enumerable.Range(startPage, (endPage + 1) - startPage);


            // update object instance with all pager properties required by the view

            TotalItems = totalItems;

            CurrentPage = currentPage;

            PageSize = pageSize;

            TotalPages = totalPages;

            StartPage = startPage;

            EndPage = endPage;

            StartIndex = startIndex;

            EndIndex = endIndex;

            Pages = pages;

        }


        public int TotalItems { get; private set; }

        public int CurrentPage { get; private set; }

        public int PageSize { get; private set; }

        public int TotalPages { get; private set; }

        public int StartPage { get; private set; }

        public int EndPage { get; private set; }

        public int StartIndex { get; private set; }

        public int EndIndex { get; private set; }

        public IEnumerable<int> Pages { get; private set; }

    }

//cách dùng trong mvc razor view

//css boostrap mặc định

    if (pager != null && pager.Pages.Any())

    {

        <nav class="table-responsive">

            <ul class="pagination justify-content-center d-flex flex-wrap">

                @if (pager.CurrentPage > 1)

                {

                    <li class="page-item">

                        <a class="page-link" href="@Url.Action("Index", "Home")">Trang đầu</a>

                    </li>

                    <li class="page-item">

                        <a class="page-link" href="@Url.Action("Index", "Home")?p=@(pager.CurrentPage - 1)">Trước</a>

                    </li>

                }


                @foreach (var p in pager.Pages)

                {

                    <li class="page-item @(p == pager.CurrentPage ? "active" : "")">

                        <a class="page-link" href="@Url.Action("Index", "Home")?p=@p">@p</a>

                    </li>

                }


                @if (pager.CurrentPage < pager.TotalPages)

                {

                    <li class="page-item">

                        <a class="page-link" href="@Url.Action("Index", "Home")?p=@(pager.CurrentPage + 1)">Tiếp</a>

                    </li>

                    <li class="page-item">

                        <a class="page-link" href="@Url.Action("Index", "Home")?p=@(pager.TotalPages)">Trang cuối</a>

                    </li>

                }

            </ul>

        </nav>

    }

02/02/2010

Dùng HtmlAgilityPack bóc tách nội dung trang web với c#

 HtmlAgilityPack là thư viện rất rất mạnh

bạn có thể bóc tách nội dung 1 trang web (1url) bất kỳ rất rất dễ nhé

Đoạn code sau làm ví dụ:
======================================

string url = "https://www.tuandev.com/2010/01/su-dung-task-trong-c.html";

HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();

HtmlAgilityPack.HtmlDocument htmlDoc = web.Load(url);

//tới đây bạn có 1 htmlDoc hoàn chỉnh rồi

//bạn có thể lấy nội dung trong từng style class như sau

//bằng cách chọn nhiều node SelectNodes hoặc 1 node SelectSingleNode

                var title = htmlDoc.DocumentNode.SelectNodes("//h3[contains(@class, 'post-title')]");

                if(title == null)

                {

                    //do somethings

                }

else{

    //do somethings

}

[Happy coding]

Đăng ký tên miền, hosting, máy chủ, thiết kế lập trình website theo yêu cầu

 Chính thức trở thành đơn vị cung cấp dịch vụ đăng ký tên miền quốc tế, tên miền Việt Nam hosting, máy chủ, cloud hosting, cloud server, ema...