intellisense دار نمودن ViewBag در ASP.NET MVC
نویسنده: امیدنصری
تاریخ: ۱۳۹۴/۰۵/۱۶ ۱۹:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System.Web;
namespace Intellisense.Models
{
public class Persons
{
// کلید
public int Id { get; set; }
// نام
public string FirstName { get; set; }
// نام خانوادگی
public string LastName { get; set; }
// نام پدر
public string FatherName { get; set; }
// سن
public int Age { get; set; }
// شماره تلفن
public int Mobile { get; set; }
// آدرس
public string Address { get; set; }
}
} using System.Collections.Generic;
using System.Web.Mvc;
using Intellisense.Models;
namespace Intellisense.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
// List of person
var listOfPerson = new List<Persons>
{
new Persons() {Id = 1, FirstName = "Jone", LastName = "liy", FatherName = "Sobin", Age = 36, Mobile = +982015222, Address = "..."},
new Persons() {Id = 2, FirstName = "kety", LastName = "sory", FatherName = "petter", Age = 19, Mobile = +962222155, Address = "..."},
};
// Set ViewBag.Persons data from listOfPerson
ViewBag.Persons = listOfPerson;
// Show and send ViewBag.Persons to view
return View();
}
}
} @{
ViewBag.Title = "ViewBag";
}
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Father Name
</th>
<th>
Age
</th>
<th>
Mobile
</th>
<th>
Address
</th>
</tr>
</thead>
<tbody>
@{foreach (var item in ViewBag.Persons)
{
<tr>
<td>
@item.Id
</td>
<td>
@item.FirstName
</td>
<td>
@item.LastName
</td>
<td>
@item.FatherName
</td>
<td>
@item.Age
</td>
<td>
@item.Mobile
</td>
<td>
@item.Address
</td>
</tr>
}
}
</tbody>
</table> @using Intellisense.Models
@{
ViewBag.Title = "ViewBag";
// روش اول
// پیشنهاد میشود که از روش اول استفاده شود
// var listOfPerson = ViewBag.Persons as IEnumerable<Persons>;
// روش دوم
// var listOfPerson = (IEnumerable<Persons>)ViewBag.Persons;
var listOfPerson = ViewBag.Persons as IEnumerable<Persons>;
}
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Father Name
</th>
<th>
Age
</th>
<th>
Mobile
</th>
<th>
Address
</th>
</tr>
</thead>
<tbody>
@{foreach (var item in listOfPerson)
{
<tr>
<td>
@item.Id
</td>
<td>
@item.FirstName
</td>
<td>
@item.LastName
</td>
<td>
@item.FatherName
</td>
<td>
@item.Age
</td>
<td>
@item.Mobile
</td>
<td>
@item.Address
</td>
</tr>
}
}
</tbody>
</table>