ما می توانیم از Viewbag فقط به عنوان Viewdata برای ذخیره کردن مدل داده استفاده کنیم. اما تفاوت Viewdata در واژه نامه آن است که اجازه string به عنوان کلید و typecasting که مورد نیاز است را می دهد در حالی که Viewbag به typecasting نیاز ندارد و یک ویژگی پویا می باشد. در این مقاله نحوه پیاده سازی Viewbag در MVC 5 را با هم خواهیم آموخت.
Viewbag در MVC 5
قطعه کد کوچک در متد Person controller’s GetEmployeeDetails
public ActionResult GetEmployeeDetails() { Employee empdetails = new Employee(); empdetails._name = "Shridhar Sharma"; empdetails._age = 25; empdetails._email = "ishriss@c-sharpcorner.com"; empdetails._city = "New Delhi"; //ViewData["Employeedetails"] = empdetails; ViewBag.Employeedetails = empdetails; return View("employeeview",empdetails); }
اینجا ویژگی های آن را در View می بینیم.
@{ Layout = null; ProjectMVC.Models.Employee empdetails = (ProjectMVC.Models.Employee)ViewBag.Employeedetails; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>employeeview</title> </head> <body> <h1>Using Viewbag</h1> NAME : @empdetails._name <br /> AGE : @empdetails._age <br /> EMAIL : @empdetails._email <br /> CITY : @empdetails._city </body> </html>
View
@model ProjectMVC.Models.Employee //model
بعد از اضافه کردن مدل بالا، ما به تمام ویژگی های آن مدل دسترسی پیدا می کنیم، مانند زیر:
این، احتمال خطای زمان کامپایل (compile time error) را کاهش می دهد.
جمع بندی
در این مقاله ما به صورت ساده روی چگونگی ذخیره اطلاعت با استفاده از Viewbag تمرکز کردیم.
آقا لینکش کجاس؟
چه لینکی دوست عزیز؟