C# 为控制器的检查输入创建自定义模型绑定
我已经使用.NET5创建了一个web应用程序,我想当用户在自定义模型绑定中创建帖子时,我检查输入价格是否超过7个数字,并且YearOfconstruction是否小于1401 post create,但如果有错误,请在前端显示,然后等待,直到用户输入最佳输入 以及编辑 如果可能,使用模型绑定存储imagename 我阅读了Microsoft文档中的自定义模型绑定,但不知道该怎么做 谢谢你的帮助 我很抱歉把代码完全留下了 房地产系统.Data.ApplicationDbContext.cs:C# 为控制器的检查输入创建自定义模型绑定,c#,asp.net-mvc,asp.net-core,C#,Asp.net Mvc,Asp.net Core,我已经使用.NET5创建了一个web应用程序,我想当用户在自定义模型绑定中创建帖子时,我检查输入价格是否超过7个数字,并且YearOfconstruction是否小于1401 post create,但如果有错误,请在前端显示,然后等待,直到用户输入最佳输入 以及编辑 如果可能,使用模型绑定存储imagename 我阅读了Microsoft文档中的自定义模型绑定,但不知道该怎么做 谢谢你的帮助 我很抱歉把代码完全留下了 房地产系统.Data.ApplicationDbContext.cs: us
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using RealEstateSystem.Models;
using RealEstateSystem.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace RealEstateSystem.Data
{
// added <AuthUser, IdentityRole, string> in below
public class ApplicationDbContext : IdentityDbContext<AuthUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<AuthUser> AuthUsers { get; set; }
public DbSet<PropertyDetails> PropertyDetails { get; set; }
// Added
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
// **************************
}
}
namespace RealEstateSystem.Models
{
public class PropertyDetails
{
public int ID { get; set; }
[MaxLength(500)]
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "عنوان")]
public string Title { get; set; }
[MaxLength(4000)]
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "توضیحات")]
public string Description { get; set; }
[Display(Name = "تصاویر")]
public string ImageName { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "قیمت")]
[DisplayFormat(DataFormatString = "{0:C1}")]
public string Price { get; set; }
[Display(Name = "منطقه")]
public string Zone { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "پارکینگ")]
public bool Parking { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "انباری")]
public bool Warehouse { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "آسانسور")]
public bool Elevator { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "طبقه")]
public string Floor { get; set; }
[Display(Name = "سال ساخت")]
[RegularExpression(@"^$|([1][3-4][0-9]{2})$",
ErrorMessage = "{0} وارد شده نامعتبر است.")]
public string YearofConstruction { get; set; }
public string UserId { get; set; }
}
namespace RealEstateSystem
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(
// Configuration.GetConnectionString("DefaultConnection")));
//services.AddDatabaseDeveloperPageExceptionFilter();
//services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
// .AddEntityFrameworkStores<ApplicationDbContext>();
//services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseMigrationsEndPoint();
}
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();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=PropertyDetails}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
namespace RealEstateSystem.Controllers
{
[Authorize]
[Area("Dashboard")]
public class PropertyDetailsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _webHostEnvironment;
// added these
private readonly UserManager<AuthenticationUser> _userManager;
private readonly SignInManager<AuthenticationUser> _signInManager;
public PropertyDetailsController(ApplicationDbContext context,
IWebHostEnvironment webHostEnvironment,
UserManager<AuthenticationUser> userManager,
SignInManager<AuthenticationUser> signInManager)
{
_context = context;
_webHostEnvironment = webHostEnvironment;
// added these
_userManager = userManager;
_signInManager = signInManager;
}
[Route("/dashboard/")]
public async Task<IActionResult> Index(string searchString)
{
// for listing all
var show = from s in _context.PropertyDetails
select s;
if (!string.IsNullOrEmpty(searchString))
{
show = show.Where(ss => ss.Title.Contains(searchString));
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View(await show.ToListAsync());
}
[AllowAnonymous]
// GET: PropertyDetails/Details/5
[Route("/details/{id?}")]
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails
.FirstOrDefaultAsync(m => m.ID == id);
if (propertyDetails == null)
{
return NotFound();
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View(propertyDetails);
}
// GET: PropertyDetails/Create
[Authorize]
[Route("/dashboard/create/")]
public IActionResult Create()
{
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/create/")]
public async Task<IActionResult> Create([Bind("ID,Title,Description,Price,Zone" +
",Parking,Warehouse,Elevator,Floor,YearofConstruction,UserId")] PropertyDetails propertyDetails,
IFormFile imgUp)
{
if (ModelState.IsValid)
{
//string uniqueFileName = null;
if (imgUp != null)
{
var dirName = "Images";
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, dirName);
// for create ImageNmae directory if does not exists
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
var fileNameCreate = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
string filePath = Path.Combine(uploadFolder, fileNameCreate);
using var fileStream = new FileStream(filePath, FileMode.Create);
imgUp.CopyTo(fileStream);
propertyDetails.ImageName = fileNameCreate;
}
// save filename in table
//propertyDetails.ImageName = uniqueFileName;
// save
_context.Add(propertyDetails);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(propertyDetails);
}
// GET: PropertyDetails/Edit/5
[Authorize]
[Route("/dashboard/edit/{id?}/")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails.FindAsync(id);
if (propertyDetails == null)
{
return NotFound();
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
// Image Id
var imageId = propertyDetails.ImageName;
ViewBag.ImageID = imageId;
// *********************
return View(propertyDetails);
}
// POST: PropertyDetails/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/edit/{id}/")]
public async Task<IActionResult> Edit(int id, [Bind("ID,Title,Description,ImageName," +
"Price,Zone,Parking,Warehouse,Elevator,Floor,YearofConstruction,UserId")] PropertyDetails propertyDetails,
IFormFile imgUp)
{
if (id != propertyDetails.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
// to contain the filename
//string uniqueFileName = null;
if (imgUp != null)
{
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, "Images");
var fileNameCreate = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
//propertyDetails.ImageName = fileNameCreate;
//uniqueFileName = imgUp.FileName;
string filePath = Path.Combine(uploadFolder, fileNameCreate);
using var fileStream = new FileStream(filePath, FileMode.Create);
imgUp.CopyTo(fileStream);
propertyDetails.ImageName = fileNameCreate;
}
// fill the image property
//propertyDetails.ImageName = uniqueFileName;
_context.Update(propertyDetails);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PropertyDetailsExists(propertyDetails.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(propertyDetails);
}
// GET: PropertyDetails/Delete/5
[Authorize]
[Route("/dashboard/delete/{id?}")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails
.FirstOrDefaultAsync(m => m.ID == id);
if (propertyDetails == null)
{
return NotFound();
}
return View(propertyDetails);
}
// POST: PropertyDetails/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/delete/{id}")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var propertyDetails = await _context.PropertyDetails.FindAsync(id);
if (propertyDetails.ImageName != null)
{
var forDelImg = propertyDetails.ImageName.ToString();
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, "Images");
var pathDelImg = Path.Combine(uploadFolder, forDelImg);
FileInfo delFile = new FileInfo(pathDelImg);
delFile.Delete();
}
_context.PropertyDetails.Remove(propertyDetails);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PropertyDetailsExists(int id)
{
return _context.PropertyDetails.Any(e => e.ID == id);
}
}
}
@model RealEstateSystem.Models.PropertyDetails
@using System.Security.Claims
@{
ViewData["Title"] = "ساخت آگهی";
var userSignedIn = User.FindFirst(ClaimTypes.NameIdentifier);
}
<div class="col-12 pb-3 pt-5 text-center">
<h1>ساخت آگهی</h1>
<hr />
<h4 class="text-black-50 pt-2">موارد زیر را وارد نمایید</h4>
</div>
<div class="col-12 text-right">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div>
<input type="hidden" asp-for="UserId" value="@ViewBag.userId" />
</div>
<div class="form-group pb-3">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Zone" class="control-label"></label>
<select asp-for="Zone" class="form-control">
<option></option>
@for (int i = 1; i <= 22; i++)
{
<option value="@i">@i</option>
}
</select>
<span asp-validation-for="Zone" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Parking" class="control-label"></label>
<select asp-for="Parking" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Parking" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Warehouse" class="control-label"></label>
<select asp-for="Warehouse" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Warehouse" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Elevator" class="control-label"></label>
<select asp-for="Elevator" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Elevator" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Floor" class="control-label"></label>
<input asp-for="Floor" class="form-control" />
<span asp-validation-for="Floor" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="YearofConstruction" class="control-label"></label>
<input asp-for="YearofConstruction" class="form-control" />
<span asp-validation-for="YearofConstruction" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Description" class="control-label"></label>
@*<input asp-for="Description" class="form-control" />*@
<textarea asp-for="Description" placeholder="توضیحات" rows="10" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="ImageName" class="control-label"></label>
@*<input asp-for="Images" class="form-control" />*@
<input type="file" name="imgUp" placeholder="آپلود" accept="image/*" asp-for="ImageName" class="form-control-file" />
<span asp-validation-for="ImageName" class="text-danger"></span>
</div>
<div class="form-group pt-3 row ">
<input type="submit" value="ثبت" class="btn btn-primary col" />
</div>
</form>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
</div>
<div class="p-3">
<a asp-action="Index" class="btn btn-outline-danger">انصراف</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
@model RealEstateSystem.Models.PropertyDetails
@{
ViewData["Title"] = "ویرایش";
}
<h1 class="text-center">ویرایش</h1>
<hr />
<div class="col-12 text-right">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form asp-area="dashboard" asp-controller="PropertyDetails" asp-action="Edit" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div>
<input type="hidden" asp-for="UserId" value="@ViewBag.userId" />
</div>
<div class="form-group pb-3">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Zone" class="control-label"></label>
<select asp-for="Zone" class="form-control">
<option></option>
@for (int i = 1; i <= 22; i++)
{
<option value="@i">@i</option>
}
</select>
<span asp-validation-for="Zone" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Parking" class="control-label"></label>
<select asp-for="Parking" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Parking" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Warehouse" class="control-label"></label>
<select asp-for="Warehouse" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Warehouse" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Elevator" class="control-label"></label>
<select asp-for="Elevator" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Elevator" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Floor" class="control-label"></label>
<input asp-for="Floor" class="form-control" />
<span asp-validation-for="Floor" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="YearofConstruction" class="control-label"></label>
<input asp-for="YearofConstruction" class="form-control" />
<span asp-validation-for="YearofConstruction" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" placeholder="توضیحات" rows="10" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<input type="hidden" asp-for="ImageName" value="@ViewBag.ImageID" />
<label asp-for="ImageName" class="control-label"></label>
<input type="file" name="imgUp" placeholder="آپلود" accept="image/*" asp-for="ImageName" class="form-control-file" />
<span asp-validation-for="ImageName" class="text-danger"></span>
</div>
<div class="form-group pt-3 row ">
<input type="submit" value="ویرایش" class="btn btn-primary col" />
</div>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<div>
<a asp-action="Index" class="btn btn-outline-danger">انصراف</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
房地产系统.startup.cs:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
using RealEstateSystem.Models;
using RealEstateSystem.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
namespace RealEstateSystem.Data
{
// added <AuthUser, IdentityRole, string> in below
public class ApplicationDbContext : IdentityDbContext<AuthUser, IdentityRole, string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<AuthUser> AuthUsers { get; set; }
public DbSet<PropertyDetails> PropertyDetails { get; set; }
// Added
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
// **************************
}
}
namespace RealEstateSystem.Models
{
public class PropertyDetails
{
public int ID { get; set; }
[MaxLength(500)]
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "عنوان")]
public string Title { get; set; }
[MaxLength(4000)]
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "توضیحات")]
public string Description { get; set; }
[Display(Name = "تصاویر")]
public string ImageName { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "قیمت")]
[DisplayFormat(DataFormatString = "{0:C1}")]
public string Price { get; set; }
[Display(Name = "منطقه")]
public string Zone { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "پارکینگ")]
public bool Parking { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "انباری")]
public bool Warehouse { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "آسانسور")]
public bool Elevator { get; set; }
[Required(ErrorMessage = "{0} را بدرستی وارد نمایید")]
[Display(Name = "طبقه")]
public string Floor { get; set; }
[Display(Name = "سال ساخت")]
[RegularExpression(@"^$|([1][3-4][0-9]{2})$",
ErrorMessage = "{0} وارد شده نامعتبر است.")]
public string YearofConstruction { get; set; }
public string UserId { get; set; }
}
namespace RealEstateSystem
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(
// Configuration.GetConnectionString("DefaultConnection")));
//services.AddDatabaseDeveloperPageExceptionFilter();
//services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
// .AddEntityFrameworkStores<ApplicationDbContext>();
//services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseMigrationsEndPoint();
}
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();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=PropertyDetails}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
namespace RealEstateSystem.Controllers
{
[Authorize]
[Area("Dashboard")]
public class PropertyDetailsController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _webHostEnvironment;
// added these
private readonly UserManager<AuthenticationUser> _userManager;
private readonly SignInManager<AuthenticationUser> _signInManager;
public PropertyDetailsController(ApplicationDbContext context,
IWebHostEnvironment webHostEnvironment,
UserManager<AuthenticationUser> userManager,
SignInManager<AuthenticationUser> signInManager)
{
_context = context;
_webHostEnvironment = webHostEnvironment;
// added these
_userManager = userManager;
_signInManager = signInManager;
}
[Route("/dashboard/")]
public async Task<IActionResult> Index(string searchString)
{
// for listing all
var show = from s in _context.PropertyDetails
select s;
if (!string.IsNullOrEmpty(searchString))
{
show = show.Where(ss => ss.Title.Contains(searchString));
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View(await show.ToListAsync());
}
[AllowAnonymous]
// GET: PropertyDetails/Details/5
[Route("/details/{id?}")]
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails
.FirstOrDefaultAsync(m => m.ID == id);
if (propertyDetails == null)
{
return NotFound();
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View(propertyDetails);
}
// GET: PropertyDetails/Create
[Authorize]
[Route("/dashboard/create/")]
public IActionResult Create()
{
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/create/")]
public async Task<IActionResult> Create([Bind("ID,Title,Description,Price,Zone" +
",Parking,Warehouse,Elevator,Floor,YearofConstruction,UserId")] PropertyDetails propertyDetails,
IFormFile imgUp)
{
if (ModelState.IsValid)
{
//string uniqueFileName = null;
if (imgUp != null)
{
var dirName = "Images";
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, dirName);
// for create ImageNmae directory if does not exists
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
var fileNameCreate = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
string filePath = Path.Combine(uploadFolder, fileNameCreate);
using var fileStream = new FileStream(filePath, FileMode.Create);
imgUp.CopyTo(fileStream);
propertyDetails.ImageName = fileNameCreate;
}
// save filename in table
//propertyDetails.ImageName = uniqueFileName;
// save
_context.Add(propertyDetails);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(propertyDetails);
}
// GET: PropertyDetails/Edit/5
[Authorize]
[Route("/dashboard/edit/{id?}/")]
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails.FindAsync(id);
if (propertyDetails == null)
{
return NotFound();
}
// Find UserId
var userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
ViewBag.userId = userID;
// *********************
// Image Id
var imageId = propertyDetails.ImageName;
ViewBag.ImageID = imageId;
// *********************
return View(propertyDetails);
}
// POST: PropertyDetails/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/edit/{id}/")]
public async Task<IActionResult> Edit(int id, [Bind("ID,Title,Description,ImageName," +
"Price,Zone,Parking,Warehouse,Elevator,Floor,YearofConstruction,UserId")] PropertyDetails propertyDetails,
IFormFile imgUp)
{
if (id != propertyDetails.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
// to contain the filename
//string uniqueFileName = null;
if (imgUp != null)
{
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, "Images");
var fileNameCreate = Guid.NewGuid() + Path.GetExtension(imgUp.FileName);
//propertyDetails.ImageName = fileNameCreate;
//uniqueFileName = imgUp.FileName;
string filePath = Path.Combine(uploadFolder, fileNameCreate);
using var fileStream = new FileStream(filePath, FileMode.Create);
imgUp.CopyTo(fileStream);
propertyDetails.ImageName = fileNameCreate;
}
// fill the image property
//propertyDetails.ImageName = uniqueFileName;
_context.Update(propertyDetails);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PropertyDetailsExists(propertyDetails.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(propertyDetails);
}
// GET: PropertyDetails/Delete/5
[Authorize]
[Route("/dashboard/delete/{id?}")]
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var propertyDetails = await _context.PropertyDetails
.FirstOrDefaultAsync(m => m.ID == id);
if (propertyDetails == null)
{
return NotFound();
}
return View(propertyDetails);
}
// POST: PropertyDetails/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize]
[Route("/dashboard/delete/{id}")]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var propertyDetails = await _context.PropertyDetails.FindAsync(id);
if (propertyDetails.ImageName != null)
{
var forDelImg = propertyDetails.ImageName.ToString();
var rootPath = _webHostEnvironment.WebRootPath;
string uploadFolder = Path.Combine(rootPath, "Images");
var pathDelImg = Path.Combine(uploadFolder, forDelImg);
FileInfo delFile = new FileInfo(pathDelImg);
delFile.Delete();
}
_context.PropertyDetails.Remove(propertyDetails);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PropertyDetailsExists(int id)
{
return _context.PropertyDetails.Any(e => e.ID == id);
}
}
}
@model RealEstateSystem.Models.PropertyDetails
@using System.Security.Claims
@{
ViewData["Title"] = "ساخت آگهی";
var userSignedIn = User.FindFirst(ClaimTypes.NameIdentifier);
}
<div class="col-12 pb-3 pt-5 text-center">
<h1>ساخت آگهی</h1>
<hr />
<h4 class="text-black-50 pt-2">موارد زیر را وارد نمایید</h4>
</div>
<div class="col-12 text-right">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div>
<input type="hidden" asp-for="UserId" value="@ViewBag.userId" />
</div>
<div class="form-group pb-3">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Zone" class="control-label"></label>
<select asp-for="Zone" class="form-control">
<option></option>
@for (int i = 1; i <= 22; i++)
{
<option value="@i">@i</option>
}
</select>
<span asp-validation-for="Zone" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Parking" class="control-label"></label>
<select asp-for="Parking" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Parking" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Warehouse" class="control-label"></label>
<select asp-for="Warehouse" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Warehouse" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Elevator" class="control-label"></label>
<select asp-for="Elevator" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Elevator" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Floor" class="control-label"></label>
<input asp-for="Floor" class="form-control" />
<span asp-validation-for="Floor" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="YearofConstruction" class="control-label"></label>
<input asp-for="YearofConstruction" class="form-control" />
<span asp-validation-for="YearofConstruction" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Description" class="control-label"></label>
@*<input asp-for="Description" class="form-control" />*@
<textarea asp-for="Description" placeholder="توضیحات" rows="10" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="ImageName" class="control-label"></label>
@*<input asp-for="Images" class="form-control" />*@
<input type="file" name="imgUp" placeholder="آپلود" accept="image/*" asp-for="ImageName" class="form-control-file" />
<span asp-validation-for="ImageName" class="text-danger"></span>
</div>
<div class="form-group pt-3 row ">
<input type="submit" value="ثبت" class="btn btn-primary col" />
</div>
</form>
</div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
</div>
<div class="p-3">
<a asp-action="Index" class="btn btn-outline-danger">انصراف</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
@model RealEstateSystem.Models.PropertyDetails
@{
ViewData["Title"] = "ویرایش";
}
<h1 class="text-center">ویرایش</h1>
<hr />
<div class="col-12 text-right">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form asp-area="dashboard" asp-controller="PropertyDetails" asp-action="Edit" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div>
<input type="hidden" asp-for="UserId" value="@ViewBag.userId" />
</div>
<div class="form-group pb-3">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Zone" class="control-label"></label>
<select asp-for="Zone" class="form-control">
<option></option>
@for (int i = 1; i <= 22; i++)
{
<option value="@i">@i</option>
}
</select>
<span asp-validation-for="Zone" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Parking" class="control-label"></label>
<select asp-for="Parking" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Parking" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Warehouse" class="control-label"></label>
<select asp-for="Warehouse" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Warehouse" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Elevator" class="control-label"></label>
<select asp-for="Elevator" class="form-control">
<option></option>
<option value="true">دارد</option>
<option value="false">ندارد</option>
</select>
<span asp-validation-for="Elevator" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Floor" class="control-label"></label>
<input asp-for="Floor" class="form-control" />
<span asp-validation-for="Floor" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="YearofConstruction" class="control-label"></label>
<input asp-for="YearofConstruction" class="form-control" />
<span asp-validation-for="YearofConstruction" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<label asp-for="Description" class="control-label"></label>
<textarea asp-for="Description" placeholder="توضیحات" rows="10" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-3">
<input type="hidden" asp-for="ImageName" value="@ViewBag.ImageID" />
<label asp-for="ImageName" class="control-label"></label>
<input type="file" name="imgUp" placeholder="آپلود" accept="image/*" asp-for="ImageName" class="form-control-file" />
<span asp-validation-for="ImageName" class="text-danger"></span>
</div>
<div class="form-group pt-3 row ">
<input type="submit" value="ویرایش" class="btn btn-primary col" />
</div>
</form>
</div>
<div class="col-md-3"></div>
</div>
</div>
<div>
<a asp-action="Index" class="btn btn-outline-danger">انصراف</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
命名空间房地产系统
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
//services.AddDbContext