ViewData, ViewBag và TempData – các tùy chọn truyền dữ liệu trong ASP.NET MVC

ASP.NET MVC cung cấp 3 tùy chọn ViewData, ViewBag và TempData để truyền dữ liệu từ controller vào view và trong request kế tiếp. ViewData và ViewBag tương tự như nhau, TempData thực hiện thêm nhiệm vụ. Chúng ta sẽ nói về điểm chính của 3 đối tượng:

Sự giống nhau giữa ViewBag và ViewData:

1. Giúp duy trì dữ liệu khi bạn di chuyển từ view vào controller

2. Được dùng để truyền dữ liệu từ controller vào view tương ứng

3. Chu kỳ tồn tại ngắn, giá trị sẽ thành null khi redirect xuất hiện. Đây là bởi vì mục tiêu thiết kế các đối tượng này là để giao tiếp giữa controller và view

Sự khác nhau giữa ViewBag và ViewData:

1. ViewData là 1 từ điển các đối tượng (dictionary) kế thừa từ lớp ViewDataDictionary và có thể truy cập dùng chuỗi key.

2. ViewBag là thuộc tính động (dynamic) mang đến thuận lợi từ đặc tính mới của C# 4.0

3. ViewData yêu cầu chuyển kiểu với các kiểu dữ liệu phức tạp và kiểm tra giá trị null để tránh lỗi

4. ViewBag không yêu cầu chuyển kiểu với các kiểu dữ liệu phức tạp

Ví dụ về ViewBag và ViewData:

public ActionResult Index()
{
    ViewBag.Name = "Ngoc Dinh NGUYEN";
    return View();
}
public ActionResult Index()
{
    ViewData["Name"] = "Ngoc Dinh NGUYEN";
    return View();
}

Trong View:

@ViewBag.Name 
@ViewData["Name"]

TempData:

TempData cũng là 1 từ điển đối tượng (dictionary) kế thừa từ lớp TempDataDictionary, được lưu trong 1 chu kỳ rất ngắn. Điểm khác biệt chính là chu kỳ sống của đối tượng. TempData giữ thông tin trong khoảng thời gian HTTP Request. Điều này có nghĩa là chỉ từ 1 trang đến 1 trang khác. Điều này cũng hoạt động với 302/303 redirection bởi vì nó cùng HTTP Request. Giúp duy trì dữ liệu khi bạn di chuyển từ 1 controller sang 1 controller khác hoặc từ hành động này sang hành động khác. Nói cách khác, khi bạn redirect, TempData giúp duy trì dữ liệu giữa các redirect. Nó là biến cục bộ dùng trong session. Nó yêu cầu chuyển kiểu cho các kiểu dữ liệu phức tạp, và kiểm tra giá trị null để tránh lỗi. Thông thường nó dùng để lưu error message hoặc validation message.

public ActionResult Index()
{
    var model = new Review()
                {
                    Body = "Start",
                    Rating = 5
                };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var model = TempData["ModelName"];
    return View(model);
}

 

Useful Tools for ASP.NET Developers

This post lists useful tools for ASP.NET developers.

Tools

  1. Visual Studio

    1. Visual Studio Productivity Power toolextensions to Visual Studio Professional (and above) with rich features like quick find, solution navigator, searchable add-reference dialog, etc.

    2. ReSharperProductivity tools for .NET developers. improves code quality, eliminates errors by providing quick fixes, etc.

    3. Web EssentialsBoosts productivity and helps if efficiently writing CSS, JavaScript, HTML, etc.

    4. MSVSMONThe Remote Debugging Monitor (msvsmon.exe) is a small application that Visual Studio connects to for remote debugging. During remote debugging, Visual Studio runs on one computer (the debugger host) and the Remote Debugging Monitor runs on a remote computer together with the applications that you are debugging.

    5. WIX toolsetbuilds Windows installation packages from XML source code.

    6. Code diggerCode Digger is Visual Studio 2012/2013 extension which helps you to understand behavior of your code.

    7. CodeMaidCodeMaid is an open source Visual Studio 2012/2013/2015 extension to cleanup, dig through and simplify your code.

    8. OzCodePowerful Visual Studio debugger visualizer.

    9. CodeRushIt is a refactoring and productivity plugin for Visual Studio.

    10. T4 Text TemplateIn Visual Studio, T4 Text Template is used as template to generate code files. The template can defined by writing text block and control logic.

    11. Indent GuidesAdds vertical lines at each indent level.

    12. PowerShell Tools: A set of tools for developing and debugging PowerShell scripts and modules in Visual Studio 2015.

  2. ASP.NET

    1. FiddlerTo capture http request/response as well as simulate request behavior.

    2. AutoMapperObject to object mapping. Like, the tool can be used to map entity objects to domain objects instead of writing manual mapping code.

    3. Unity/Ninject/Castle Windsor/StructureMap/Spring.NetDependency injection framework. There are a lot of DI frameworks available.

    4. .NET Reflector.NET assembly decompiler.

    5. dotPeek.NET assembly decompiler.

    6. ILSpy.NET assembly decompiler.

    7. memprofilerPowerful tool to find memory leak and optimize memory usage.

    8. PostSharpRemoves repetitive coding and prevent code bloating due to cross-cutting concerns with aspect oriented programming.

    9. ASPhere: Web.config editor with GUI.

  3. WCF

    1. SOAP UIAPI testing tool which supports all standard protocol and technologies.

    2. WireSharkIt is a network protocol analyzer for Unix and Windows. It can capture traffic at TCP level and help you see soap envelop.

    3. Svc TraceViewerprovides better view of huge trace file which is produced by WCF.

    4. Svc Config Editor: GUI tool for managing WCF related configurations.

  4. MSMQ

    1. ​​​​​​​QueueExplorer 3.4copy, move or delete messages, save and load, stress test, view and edit full message bodies (with special support for .Net serialized objects), and much more for MSMQ.

  5. LINQ

    1. LINQ Pad?: LINQPad is a light weight tool to test linq queries against SQL Server database. It can also test code snippet written in different .NET languages like C#, VB, etc.

    2. LINQ InsightLINQ Insight Express is a Visual Studio add-in that allows you to analyze your LINQ queries at design-time and simplifies writing and debugging LINQ queries.

  6. RegEx

    1. RegEx tester: Extension for Visual Studio for regular expression testing.

    2. regexr: Online RegEx develop and testing tool.

    3. regexpalOnline RegEx develop and testing tool.

    4. Expresso: Expresso is a destop tool for RegEx develop and testing.

    5. RegexMagic : Tools to auto-generate regular expression from text pattern. The user need to feed the pattern by marking the substrings and selecting different options. Based on that the regex will be auto-generated. The tools also generates the required code in different language.

  7. Javascript/JQuery/AngularJS

    1. JSHint: JavaScript code quality tool. There is one more tool JSLine which enforces stricter rules.

    2. JSFiddle: It provides an environment inside the browser to test HTML, CSS and Javascript/JQuery.

    3. Protractor: End to end framework to test angular application.

  8. SQL Server

    1. SQL ProfilerSQL trace for monitoring instance of database engine.

    2. SQL Sentry Plan explorerThe tool provides better graphical view of SQL Query execution plan.

    3. SQL CompleteProvides Intellisense functionality and Improved SQL Formatter in SQL Server Management Studio and Visual Studio.

    4. NimbleTextText manipulation and code generation tool.

    5. Query Express: Light weight SQL Query analyzer like tool.

    6. IO MeterProvides detail of IO subsystem.

    7. sqldecryptorDecrypts SQL Server objects like Stored Procedures, Functions, Triggers, Views which were encrypted WITH ENCRYPTION option.

    8. SpatialViewerTo view and create spatial data.

    9. ClearTraceimports trace and profiler files into SQL Server and displays summary performance information.

    10. Internals Viewer for SQL ServerInternals Viewer is a tool for looking into the SQL Server storage engine and seeing how data is physically allocated, organized and stored.

    11. PALreads in a perfmon log and analyzes it using known thresholds.

    12. sqlquerystressassists with performance stress testing of T-SQL queries and routines.

  9. NHibernate

    1. NHibernate Mapping Generator generates NHibernate mapping files and corresponding domain classes from existing DB tables.

  10. Tally

    1. Tally ERP 9

    2. Tally dlla dynamic link library for .net to integrate your application with Tally Accounting software to push and pull data progrmmatically.

  11. Code Review

    1. StyleCopStyleCop is a static code analysis tool which enforces set of configured style and consistency rules for your C# source code. It can be run from inside of Visual Studio or integrated into an MSBuild project. 

    2. FxCop?: FxCop is a static code analysis tool which enforces development standards by analyzing .NET assembly.

  12. Traffic Capture

    1. WireShark: It is a network protocol analyzer for Unix and Windows. It can capture traffic at TCP level. 

    2. HTTP Monitorenables the developer to view all the HTTP traffic between your computer and the Internet. This includes the request data (such as HTTP headers and form GET and POST data) and the response data (including the HTTP headers and body).

  13. Diagnostic

    1. Glimpse: Provides server side diagnostic data. Like, for an ASP.NET MVC project, you need to add it from NuGet. The Glimpse data can show you latency at different levels and really indicate areas where you can optimize your code/solution to boost performance.

  14. Performance

    1. PerfMon: monitors system performance using performance counters.

    2. yslowYSlow analyzes web pages and indicates why they’re slow based on Yahoo!’s rules for high performance web sites.

  15. Code Converter

    1. Telerik Code ConverterC# to VB and VB to C# code converter. It is an online editor. But you can choose 'Batch Converter' and upload files in zip format.

  16. Data Extraction and Loading

    1. FileHelpers.NET library to import/export data from fixed length or delimited records in files, strings or streams.

    2. LogParser: You can write SQL to queries against a variety of log files and export the data to a variety of destinations like SQL tables, CSV files.

  17. Screen Recording

    1. Wink: Presentation creation software. Using Wink, you can capture screenshots, add explanations, comments, etc. and create the demo.

  18. Text Editor

    1. Notepad++: Source code editor. 

    2. Notepad2Light-weight feature rich Notepad-like text editor.

    3. sublimetext: A feature rich text editor.

  19. Documentation

    1. GhostDocGhostDoc is a Visual Studio extension that automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information.

    2. helpndoc: helpndoc is a tool to create help files. It can generate files in different formats from a single source.

  20. Others

    1. FileZilla: FileZilla is a free FTP solution. FileZilla Client for FTP file uploadingand FileZilla Server for file share.

    2. TreeTrimTreeTrim is a tool that trims the source code tree. It removes debug files, source control bindings, and temporary files.

    3. BrowserStack: cross browser testing website.

    4. Firebug: Feature rich firefox add on for CSS, HTML and JavaScript development on generated web page.

    5. BugShooting: Screen capture software which takes a screen shot and attaches to the work items, bugs, issue tracker items, etc.

    6. Postman: REST client. You can send http request and analyze response for REST applications.

    7. Web developer checklist: the checklist ensures best practices for web development.

    8. XRAY: Firefox add-on. Feature rich bookmarklet. Provides information about element in webpage.

    9. PowerGUIhelps to quickly adopt and use PowerShell to efficiently manage your entire Windows environment.