تمرير البيانات من Action Method ل View
-
اهلا وسهلا فيكم
الهدف من هذا الدرس هو تعلم كيف نرسل البيانات من Action الى View بعد معالجتها،وطرق ارسال هذه البيانات
هناك 4 طرق مختلفة لتمرير البيانات من Action Method الى View وهذه الطرق هي:
- View Model Object
- ViewBag
- TempData
- Session Variable
وحتي نفهم الموضوع خلونا نطبق امثلة عمليه على كل نوع.
تمام التمام
النوع الأول View Model Object
في هذه الطريقة يتم ارجاع البيانات من action الى view عن طريق Model Object .
تمام نرجع لمشروعنا StudentAcademy وبعدها ننتقل الى StudentsController وبعدها تضيف action جديد باسم StudentInfo ونضيف الكود التالي:
public IActionResult StudentInfo()
{
StudentsModel _Student = new StudentsModel();
_Student.CustomerNo = "2100001";
_Student.FullName = "Hatem Altalafha";
_Student.Birthday = Convert.ToDateTime("01/01/1980");
_Student.Gender = 1;
_Student.Nationality = 1;
_Student.Address = "Jordan";
_Student.UserName = "Hatem";
_Student.Password = "abc123";
_Student.Email = "[email protected]";
_Student.Mobile = "000000000";
_Student.Note = "";
return View(_Student);
}
هذه الطريقة تعتمد على Model لاحظ في هذا المثال ان استخدمنا Model من نوع StudentsModel ،وهذا Model كنا عملناه من قبل، للتذكير الكود الخاص بهذا Model بكون :
في هذا action استخدمنا بعض الخصائص property من StudentModel وخزنا فيها بيانات مثل (رقم العيل، الاسم ، تاريخ الميلاد ... الخ) واخر الaction استدعينا View وارسلنا لها Model من البيانات
كود الاستدعاء
return View(_Student);
@model StudentsModel
@{
ViewData["Title"] = "StudentInfo";
}
<h2>Student Info</h2>
<p>Customer No : @Model.StudentNo</p>
<p>Full Name: @Model.FullName</p>
<p>Birthday: @Model.Birthday</p>
<p>Gender : @Model.Gender </p>
<p>Nationality : @Model.Nationality </p>
<p>Address : @Model.Address </p>
<p>UserName : @Model.UserName </p>
<p>Password : @Model.Password</p>
<p>Email : @Model.Email </p>
<p>Mobile : @Model.Mobile </p>
<p>Customer No : @Model.StudentNo</p>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Models
{
public class StudentsModel
{
public string CustomerNo { get; set; }
public string FullName { get; set; }
public DateTime Birthday { get; set; }
public int Gender { get; set; }
public int Nationality { get; set; }
public string Address { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Note { get; set; }
public DateTime CurrentDate { get; set; }
}
}
public IActionResult StudentInfo()
{
StudentsModel _Student = new StudentsModel();
_Student.CustomerNo = "2100001";
_Student.FullName = "Hatem Altalafha";
_Student.Birthday = Convert.ToDateTime("01/01/1980");
_Student.Gender = 1;
_Student.Nationality = 1;
_Student.Address = "Jordan";
_Student.UserName = "Hatem";
_Student.Password = "abc123";
_Student.Email = "[email protected]";
_Student.Mobile = "000000000";
_Student.Note = "";
_Student.CurrentDate = DateTime.Now;
return View(_Student);
}
model StudentsModel
@{
ViewData["Title"] = "StudentInfo";
}
<p>Current Date: @Model.CurrentDate</p>
<hr />
<h2>Student Info</h2>
<p>Customer No : @Model.CustomerNo</p>
<p>Full Name: @Model.FullName</p>
<p>Birthday: @Model.Birthday</p>
<p>Gender : @Model.Gender </p>
<p>Nationality : @Model.Nationality </p>
<p>Address : @Model.Address </p>
<p>UserName : @Model.UserName </p>
<p>Password : @Model.Password</p>
<p>Email : @Model.Email </p>
<p>Mobile : @Model.Mobile </p>
https://localhost:44382/Students/StudentInfo

@model DateTime
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Model: @Model and Year: @Model.Year
</body>
</html>
@model DateTime
Model: @Model and Year: @Model.Year
retrun View((object)"How are you");
public IActionResult StudentInfo()
{
StudentsModel _Student = new StudentsModel();
_Student.CustomerNo = "2100001";
_Student.FullName = "Hatem Altalafha";
_Student.Birthday = Convert.ToDateTime("01/01/1980");
_Student.Gender = 1;
_Student.Nationality = 1;
_Student.Address = "Jordan";
_Student.UserName = "Hatem";
_Student.Password = "abc123";
_Student.Email = "[email protected]";
_Student.Mobile = "000000000";
_Student.Note = "";
_Student.CurrentDate = DateTime.Now;
ViewBag.UserName = "Admin";
return View(_Student);
}
ViewBag.ViewBagName="Value";
@ViewBag.(Variable Name)
@model StudentsModel
@{
ViewData["Title"] = "StudentInfo";
}
Welcome ,@ViewBag.UserName
<hr />
<p>Current Date: @Model.CurrentDate</p>
<hr />
<p>Current Year: @Model.CurrentDate.Year</p>
<h2>Student Info</h2>
<p>Customer No : @Model.CustomerNo</p>
<p>Full Name: @Model.FullName</p>
<p>Birthday: @Model.Birthday</p>
<p>Gender : @Model.Gender </p>
<p>Nationality : @Model.Nationality </p>
<p>Address : @Model.Address </p>
<p>UserName : @Model.UserName </p>
<p>Password : @Model.Password</p>
<p>Email : @Model.Email </p>
<p>Mobile : @Model.Mobile </p>
https://localhost:44382/Students/StudentInfo

- تعد ViewBag طريقة خفيفة لنقل القيم من Controllers إلى Views.
- تنقل ViewBag البيانات فقط من controller الى view، وليس العكس.
- تفقد ViewBag قيمتها في حالة حدوث إعادة التوجيه بين View. (من الخطأ في المشاريع الحقيقة استخدامها لعرض اسم المستخدم الحالي، لأنه سوف يفقد قيمته بمجرد الانتقال بين Views)
- يمكن أن تحتوي على كائن من النوع primitive أو complex.
- يمكنك تعيين أي عدد من properties values إلى ViewBag.
public IActionResult NewStudent()
{
TempData["UserName"] = "Admin";
return View();
}
TempData["ViewBagName"] = "Value";
model StudentsModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
Welcome ,@TempData["UserName"]
<hr />
<div class="container">
<form method="post" asp-action="ReceivedDataByModelBinding">
<div class="form-group">
<label>CustomerNo:</label>
<input class="form-control" asp-for="CustomerNo" />
</div>
<div class="form-group">
<label>FullName:</label>
<input class="form-control" asp-for="FullName" />
</div>
<div class="form-group">
<label>Birthday:</label>
<input class="form-control" asp-for="Birthday" />
</div>
<div class="form-group">
<label>Gender:</label>
<select class="form-control" asp-for="Gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group">
<label>Nationality:</label>
<select class="form-control" asp-for="Nationality">
<option value="M">Jordan</option>
<option value="F">Saudi Aribae</option>
<option value="F">UAE</option>
</select>
</div>
<div class="form-group">
<label>Address:</label>
<input class="form-control" asp-for="Address" />
</div>
<div class="form-group">
<label>UserName:</label>
<input class="form-control" asp-for="UserName" />
</div>
<div class="form-group">
<label>Password:</label>
<input class="form-control" asp-for="Password" />
</div>
<div class="form-group">
<label>Email:</label>
<input class="form-control" asp-for="Email" />
</div>
<div class="form-group">
<label>Mobile:</label>
<input class="form-control" asp-for="Mobile" />
</div>
<div class="form-group">
<label>Note:</label>
<input class="form-control" asp-for="Note" />
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</body>
</html>
@model StudentsModel
@{
ViewData["Title"] = "ReceivedDataByModelBinding";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ReceivedDataByModelBinding</title>
</head>
<body>
Welcome ,@TempData["UserName"]
<hr />
<h1>Customer Number :@Model.CustomerNo ,Full Name is @Model.FullName, Birthday @Model.Birthday</h1>
</body>
</html>

TempData["UserName"] = "Admin";
public IActionResult ReceivedDataByModelBinding(StudentsModel Student)
{
TempData["UserName"] = "Admin";
return View("ReceivedDataByModelBinding", Student);
}

public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSession();
}
الامر | المكان |
services.AddSession() | ()ConfigureServices في ملف Startup |
app.UseSession() | ()Configure ملف Startup |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StudentsAcademy.Services;
using StudentsAcademy.Middleware;
using StudentsAcademy.Share;
using Microsoft.EntityFrameworkCore;
using StudentsAcademy.Interface;
using StudentsAcademy.Repository;
using StudentsAcademy.Models;
namespace StudentsAcademy
{
public class Startup
{
public IConfiguration Configuration { get; }
private IWebHostEnvironment env;
public Startup(IConfiguration configuration, IWebHostEnvironment hostEnv)
{
Configuration = configuration;
env = hostEnv;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICourses>(provider =>
{
if (env.IsDevelopment())
{
var x = provider.GetService<CourseRepository>();
return x;
}
else
{
return new ClassRoomsRepository();
}
});
// services.AddTransient<ICourses>();
services.Configure<Connections>(Configuration.GetSection("ConnectionStrings"));
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//services.AddTransient<ICourses, CourseRepository>();
//services.AddScoped<ICourses, CourseRepository>();
//services.AddSingleton<ICourses, CourseRepository>();
services.AddTransient<IStorage, StorageRepository>();
services.AddTransient<CourseSum>();
services.AddSingleton<TotalStudents>();
services.Configure<MyJson>(Configuration);
services.AddControllersWithViews();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
if ((Configuration.GetSection("Middleware")?.GetValue<bool>("EnableResponseEditingMiddleware")).Value)
{
app.UseMiddleware<ResponseEditingMiddleware>();
}
if ((Configuration.GetSection("Middleware")?.GetValue<bool>("EnableRequestEditingMiddleware")).Value)
{
app.UseMiddleware<RequestEditingMiddleware>();
}
if ((Configuration.GetSection("Middleware")?.GetValue<bool>("EnableShortCircuitMiddleware")).Value)
{
app.UseMiddleware<ShortCircuitMiddleware>();
}
if ((Configuration.GetSection("Middleware")?.GetValue<bool>("EnableContentMiddleware")).Value)
{
app.UseMiddleware<ContentMiddleware>();
}
//app.UseMiddleware<ResponseEditingMiddleware>();
//app.UseMiddleware<RequestEditingMiddleware>();
//app.UseMiddleware<ShortCircuitMiddleware>();
//app.UseMiddleware<ContentMiddleware>();
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
HttpContext.Session.SetString("SessionName",SessionValue ));
public IActionResult NewStudent()
{
HttpContext.Session.SetString("UserName", "Admin");
//TempData["UserName"] = "Admin";
return View();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICourses>(provider =>
{
if (env.IsDevelopment())
{
var x = provider.GetService<CourseRepository>();
return x;
}
else
{
return new ClassRoomsRepository();
}
});
// services.AddTransient<ICourses>();
services.Configure<Connections>(Configuration.GetSection("ConnectionStrings"));
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//services.AddTransient<ICourses, CourseRepository>();
//services.AddScoped<ICourses, CourseRepository>();
//services.AddSingleton<ICourses, CourseRepository>();
services.AddTransient<IStorage, StorageRepository>();
services.AddTransient<CourseSum>();
services.AddSingleton<TotalStudents>();
services.Configure<MyJson>(Configuration);
services.AddControllersWithViews();
services.AddSession();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
@using StudentsAcademy
@using StudentsAcademy.Models
@using Microsoft.AspNetCore.Http
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model StudentsModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
@*Welcome ,@TempData["UserName"]*@
Welcome,@HttpContextAccessor.HttpContext.Session.GetString("UserName")
<hr />
<div class="container">
<form method="post" asp-action="ReceivedDataByModelBinding">
<div class="form-group">
<label>CustomerNo:</label>
<input class="form-control" asp-for="CustomerNo" />
</div>
<div class="form-group">
<label>FullName:</label>
<input class="form-control" asp-for="FullName" />
</div>
<div class="form-group">
<label>Birthday:</label>
<input class="form-control" asp-for="Birthday" />
</div>
<div class="form-group">
<label>Gender:</label>
<select class="form-control" asp-for="Gender">
<option value="M">Male</option>
<option value="F">Female</option>
</select>
</div>
<div class="form-group">
<label>Nationality:</label>
<select class="form-control" asp-for="Nationality">
<option value="M">Jordan</option>
<option value="F">Saudi Aribae</option>
<option value="F">UAE</option>
</select>
</div>
<div class="form-group">
<label>Address:</label>
<input class="form-control" asp-for="Address" />
</div>
<div class="form-group">
<label>UserName:</label>
<input class="form-control" asp-for="UserName" />
</div>
<div class="form-group">
<label>Password:</label>
<input class="form-control" asp-for="Password" />
</div>
<div class="form-group">
<label>Email:</label>
<input class="form-control" asp-for="Email" />
</div>
<div class="form-group">
<label>Mobile:</label>
<input class="form-control" asp-for="Mobile" />
</div>
<div class="form-group">
<label>Note:</label>
<input class="form-control" asp-for="Note" />
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</body>
</html>
Welcome,@HttpContextAccessor.HttpContext.Session.GetString("UserName")

HttpContext.Session.SetInt32("MySession", 100);
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ICourses>(provider =>
{
if (env.IsDevelopment())
{
var x = provider.GetService<CourseRepository>();
return x;
}
else
{
return new ClassRoomsRepository();
}
});
// services.AddTransient<ICourses>();
services.Configure<Connections>(Configuration.GetSection("ConnectionStrings"));
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//services.AddTransient<ICourses, CourseRepository>();
//services.AddScoped<ICourses, CourseRepository>();
//services.AddSingleton<ICourses, CourseRepository>();
services.AddTransient<IStorage, StorageRepository>();
services.AddTransient<CourseSum>();
services.AddSingleton<TotalStudents>();
services.Configure<MyJson>(Configuration);
services.AddControllersWithViews();
services.AddSession();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Models
{
public class LoginAuthentication
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Models
{
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
}
using Microsoft.AspNetCore.Mvc;
using StudentsAcademy.Interface;
using StudentsAcademy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace StudentsAcademy.Controllers
{
public class LoginController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Hello()
{
ViewBag.Message = "Hello World";
return View();
}
public IActionResult CheckUserNamePassword()
{
HttpContext.Session.Set("UserDetails", new LoginModel
{
UserName = "Admin",
Password = "Admin"
});
return RedirectToAction("StudentInfo", "Students");
}
}
}

@model LoginModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<form method="post" asp-action="CheckUserNamePassword">
<div class="form-group">
<label>UserName:</label>
<input class="form-control" asp-for="UserName" />
</div>
<div class="form-group">
<label>Password:</label>
<input class="form-control" asp-for="Password" />
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</body>
</html>
<form method="post" asp-action="CheckUserNamePassword">
<input class="form-control" asp-for="UserName" />
<input class="form-control" asp-for="Password" />
@model LoginModel
https://localhost:44382/Login

var userContent = HttpContext.Session.Get<LoginModel>("UserDetails");
ViewBag.UserName = userContent.UserName;

services.AddSession(options => {
options.Cookie.Name = "UserDetails.Session"; // Cookie name
options.IdleTimeout = TimeSpan.FromMinutes(30); // Expire Time after 30 min
});
اترك تعليقك