I try to display datas from a list in an html page by grouping by productType
Her is my code :
Models:
public enum ProductType {
HOTEL_PRODUCT("HOTEL_PRODUCT", "Hotel - Product"),
HEBERG_PRODUCT("HEBERG_PRODUCT", "Lodging - Product");
private final String code;
private final String description;
private ProductType(String code, String description) {
this.code = code;
this.description = description;
}
//Getters and Setters....
.
public class PriceProduct {
private BigDecimal price;
private BigDecimal taxes;
public PriceProduct() {
super();
}
public PriceProduct(BigDecimal price, BigDecimal taxes) {
super();
this.price = price;
this.taxes = taxes;
}
// Getters and Setters ....
.
public class Product {
private String productName;
private ProductType productType;
private PriceProduct priceProduct;
public Product() {
super();
}
public Product(String productName, ProductType productType, PriceProduct priceProduct) {
super();
this.productName = productName;
this.productType = productType;
this.priceProduct = priceProduct;
} // Getters and Setters
.
In the controller i methode:
#RequestMapping(value = "/all", method = RequestMethod.GET)
public List<Product> findAll(Model model){
List<Product> products=new ArrayList<>();
products.add(new Product("HAMILTON", ProductType.HOTEL_PRODUCT, new PriceProduct(new BigDecimal(200), new BigDecimal(20)) ));
products.add(new Product("SWANZI", ProductType.HEBERG_PRODUCT, new PriceProduct(new BigDecimal(100), new BigDecimal(10)) ));
products.add(new Product("PAPILLION", ProductType.HOTEL_PRODUCT, new PriceProduct(new BigDecimal(350), new BigDecimal(70)) ));
products.add(new Product("FORKAT", ProductType.HEBERG_PRODUCT, new PriceProduct(new BigDecimal(399), new BigDecimal(65)) ));
model.addAttribute("products", products);
return products;
}
This is my html page:
<div th:each="prod,row : ${products}" th:object="${prod}" style="width: 600px;" class="container">
<div class="col-xs-12" th:text="*{productType.description}"></div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" th:text="*{productName}"></div>
<div class="col-xs-3" >Price</div>
<div class="col-xs-3" >Taxes</div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" ></div>
<div class="col-xs-3" th:text="*{priceProduct.price}"></div>
<div class="col-xs-3" th:text="*{priceProduct.taxes}"></div>
</div>
But when i display all that it duplicate the productType:
I am looking for some think like this :
I found this solution bellow but if you can propose an other one more simple, so do it :)
<div th:each="prod,row : ${products.?[productType == T(com.test.model.ProductType).HOTEL_PRODUCT]}" th:object="${prod}" style="width: 600px;" class="container" >
<div class="col-xs-12" th:text="*{productType.description}" th:if="${row.first}"></div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" th:text="*{productName}"></div>
<div class="col-xs-3" >Price</div>
<div class="col-xs-3" >Taxes</div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" ></div>
<div class="col-xs-3" th:text="*{priceProduct.price}"></div>
<div class="col-xs-3" th:text="*{priceProduct.taxes}"></div>
</div>
<div th:each="prod,row : ${products.?[productType == T(com.test.model.ProductType).HEBERG_PRODUCT]}" th:object="${prod}" style="width: 600px;" class="container" >
<div class="col-xs-12" th:text="*{productType.description}" th:if="${row.first}"></div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" th:text="*{productName}"></div>
<div class="col-xs-3" >Price</div>
<div class="col-xs-3" >Taxes</div>
<div class="col-xs-12"></div>
<div class="col-xs-3"></div>
<div class="col-xs-3" ></div>
<div class="col-xs-3" th:text="*{priceProduct.price}"></div>
<div class="col-xs-3" th:text="*{priceProduct.taxes}"></div>
</div>
Related
Welcome,
I have several pictures, when I click on one it should take me to another window of this picture.
But this does not happen, but I get this window with this error message:
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[FirstProject.Models.student]', but
this dictionary requires a model item
I will put the codes related to the problem:
HomeController
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FirstProject.Controllers
{
public class HomeController : Controller
{
level_8_coursesEntities db = new level_8_coursesEntities();
public ActionResult Index()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Numberofstudents()
{
List<level_8_courses> list = db.level_8_courses.ToList();
return View(list);
}
public ActionResult Students(int? id)
{
List<student> studentlist = null;
if (id.HasValue)
{
studentlist = db.students.Where(x => x.corId == id).ToList();
}
else
{
// Set the `studentlist` to some default value when `id` doesn't defined or not a number.
studentlist = null;
}
return View(studentlist);
}
Number of students.chtml
#{
ViewBag.Title = "Numberofstudents";
}
#using FirstProject.Models;
#model List<level_8_courses>
<div class="container">
<section class="page-section portfolio" id="portfolio">
<div class="container">
<!-- Portfolio Section Heading-->
<h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Numberofstudents</h2>
<!-- Icon Divider-->
<div class="divider-custom">
<div class="divider-custom-line"></div>
<div class="divider-custom-icon"><i class="fas fa-star"></i></div>
<div class="divider-custom-line"></div>
</div>
<!-- Portfolio Grid Items-->
<div class="row justify-content-center">
<!-- Portfolio Item 1 data-bs-target="#portfolioModal" -->
#foreach (var item in Model)
{
<div class="col-md-6 col-lg-4 mb-5">
<a href="/Home/students/#item.Id">
<div class="portfolio-item mx-auto" data-bs-toggle="modal">
<div class="portfolio-item-caption d-flex align-items-center justify-content-center h-100 w-100">
<div class="portfolio-item-caption-content text-center text-white"><i class="fas fa-plus fa-3x"></i></div>
</div>
<img class="img-fluid" style="height:100px;width:100px" src="#item.photo" alt="" />
</div>
</a>
<div style="text-align:center">
<h5>#item.corName</h5>
</div>
</div>
}
</div>
</div>
</section>
</div>
Students.chtml
#using FirstProject.Models;
#model List<student>
<div class="container">
<div class="row">
#foreach (var item in Model)
{
<div class="card col-sm-6">
<div class="card" style="width: 18rem;">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.sName</h5>
<p class="card-text">#item.sEmail</p>
</div>
</div>
</div>
}
</div>
</div>
Thanks
fix students action, if you don't have any students create an empty list as a model, and remove studentlist = null;
List<student> studentlist = null
if (id!=null && id > 0)
studentlist = db.students.Where(x => x.corId == id).ToList();
if(studentlist==null) studentslist= new List<student>();
return View(studentlist);
I am working on an application where I want to load View Component. On local machine it is working with out any problem or error but when I make deployment it is not working properly and gives me error of 500. Here is my implementation.
Jquery Function
function UPdateHistoryGrid() {
$("#notification-history").empty();
var _url = '#Url.Action("NotificationHistory", "Notification")';
$.ajax({
type: "GET",
url: _url,
success: function (result) {
$("#notification-history").html(result);
},
error(res) {
console.log(res)
}
});
};
Controller action method
public IActionResult NotificationHistory()
{
return ViewComponent("NotificationHistory");
}
View Component .cs
public class NotificationHistoryViewComponent : ViewComponent
{
protected readonly IHttpNetClientService _apiService;
IUserProfileInfoProvider _userInfoProvider;
public NotificationHistoryViewComponent(IHttpNetClientService HttpService,
IUserProfileInfoProvider userInfo)
{
_apiService = HttpService;
_userInfoProvider = userInfo;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = new NotificationParentModel();
var NotificationApiJsonResult = await _apiService.GetAllAsync(Notification_API_URL.GetAllNotificationsHistory.GetEnumDescription(), _userInfoProvider.GetUserInfo().Id, _userInfoProvider.GetToken());
var notificationData = JsonConvert.DeserializeObject<ResponseDTO<IEnumerable<GMDNotificationDTO>>>(NotificationApiJsonResult);
model.NotificaitonList = notificationData.Data.ToList();
return await Task.FromResult((IViewComponentResult)View("NotificationHistory", model));
}
}
View Code
#using GMDSuperAdmin.Helper
#model GMDSuperAdmin.Models.NotificationParentModel
<div class="notificationCard-Container text-container #(!Model.IsToday ? "mt-5" : "") bg-white px-0">
<div class="position-relative">
<h5 class="text-center py-3">Notification History</h5>
</div>
#{
if (Model.NotificaitonList.Count() > 0)
{
foreach (var item in Model.NotificaitonList)
{
<div class="row message-row message-row-2 mx-0 py-1" id="clickable-row">
<div class="row mx-0 main-notificationRow justify-content-between" id="translate-row" #*onclick="selectedNotification(this, #item.NOtificationId)"*#>
<div class="d-flex align-items-center py-2">
<div class="notification-list_img document-noti mx-2 mt-1 mx-lg-3">
<i class="fas fa-file-alt"></i>
</div>
<div class="notifierInfo">
<p class="message-paragraph mb-0">
#item.NotificationDescription
</p>
</div>
</div>
<div class="notification-time pt-1 pb-2 mx-2">
<p class="message-paragraph text-right mb-0">
#(DateTimeHelper.TimeAgo(item.CreatedDate))
</p>
</div>
</div>
</div>
}
}
else
{
<div class="row message-row py-1 mx-0" id="clickable-row">
<div class="row mx-0 main-notificationRow" id="translate-row">
<div class="col-12 col-lg-12">
<p class="message-paragraph text-muted mb-0 text-center">
<b>No Notification Found!</b>
</p>
</div>
</div>
</div>
}
}
</div>
Please rename your view component as default. NotificatioHistory.cshtml to Default.cshtml. Some time it makes issues with custom names on production so the recommended way is to use Default.cshtml.
public class NotificationHistoryViewComponent : ViewComponent
{
protected readonly IHttpNetClientService _apiService;
IUserProfileInfoProvider _userInfoProvider;
public NotificationHistoryViewComponent(IHttpNetClientService HttpService,
IUserProfileInfoProvider userInfo)
{
_apiService = HttpService;
_userInfoProvider = userInfo;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var model = new NotificationParentModel();
var NotificationApiJsonResult = await _apiService.GetAllAsync(Notification_API_URL.GetAllNotificationsHistory.GetEnumDescription(),
_userInfoProvider.GetUserInfo().Id, _userInfoProvider.GetToken());
var notificationData = JsonConvert.DeserializeObject<ResponseDTO<IEnumerable<GMDNotificationDTO>>>(NotificationApiJsonResult);
model.NotificaitonList = notificationData.Data.ToList();
return View(model); //// Change this ...
}
}
I am working with the partial views to attain a functionality in which I have to delete data from two tables having a one to many relationship in database. For this, I am using same “Delete” function in controller for both tables. I have added two models for these tables in the Delete view using ViewModels and have rendered both partial views in the main Delete Page to display relevant data on each delete view but after doing all this coding I am getting the following error.
The model item passed into the dictionary is of type 'System.Data.Entity.DynamicProxies.tblPatientBill_804486DE0CB5E4B1C416CFC35E7B001C20B1FDB3674F40F1811012FFC9BAA908', but this dictionary requires a model item of type 'HMS.ViewModels.DeleteViewModel'.
Here is my Code Details:
PatientsBillController:
public ActionResult Delete(int? id,DeleteViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
PatientsBillViewModel billmodell = new PatientsBillViewModel();
PatientsBillDetailViewModel billdetailmodell = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (billdetail == null)
{
if (bill == null)
{
return HttpNotFound();
}
else
{
billmodell.ID = bill.ID;
billmodell.PatientAppointmentID = bill.PatientAppointmentID;
billmodell.BillNo = bill.BillNo;
billmodell.Amount = bill.Amount;
billmodell.Discount = bill.Discount;
billmodell.CreatedAt = bill.CreatedAt;
billmodell.CreatedBy = bill.CreatedBy;
billmodell.Description = bill.Description;
return View(billmodell);
}
}
else
{
billdetailmodell.ID = billdetail.ID;
billdetailmodell.PatientBillID = billdetail.PatientBillID;
billdetailmodell.Amount = billdetail.Amount;
billdetailmodell.CreatedAt = billdetail.CreatedAt;
billdetailmodell.CreatedBy = billdetail.CreatedBy;
billdetailmodell.Description = billdetail.Description;
return View(billdetail);
}
}
Delete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "Delete";
Layout = null;
}
#{Html.RenderPartial("PatientsBillDelete", Model); }
#{Html.RenderPartial("PatientsBillDetail", Model); }
ViewModel.cs:
public class DeleteViewModel
{
public PatientsBillViewModel billmodel { set; get; }
public PatientsBillDetailViewModel billdetailmodel { set; get; }
}
public class PatientsBillViewModel
{
public int ID { get; set; }
public int PatientAppointmentID { get; set; }
public string BillNo { get; set; }
public float Amount { get; set; }
public float Discount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
public class PatientsBillDetailViewModel
{
public int ID { get; set; }
public int PatientBillID { get; set; }
public float Amount { get; set; }
public string CreatedAt { get; set; }
public string CreatedBy { get; set; }
public string Description { get; set; }
}
PartialViews are:
PatientBillDelete.cshtml
PatientBillDetail.cshtml
PatientBillDelete.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.ID)
<br />
#Html.DisplayFor(m => m.billmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.PatientAppointmentID)
<br />
#Html.DisplayFor(m => m.billmodel.PatientAppointmentID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.BillNo)
<br />
#Html.DisplayFor(m => m.billmodel.BillNo)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Amount)
<br />
#Html.DisplayFor(m => m.billmodel.Amount)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Discount)
<br />
#Html.DisplayFor(m => m.billmodel.Discount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedAt)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.CreatedBy)
<br />
#Html.DisplayFor(m => m.billmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(m => m.billmodel.Description)
<br />
#Html.DisplayFor(m => m.billmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(m => m.billmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
PatientsBillDetail.cshtml
#using HMS.ViewModels
#model HMS.ViewModels.DeleteViewModel
#{
ViewBag.Title = "PatientsBill Delete";
}
<section class="content">
<div class="container-fluid">
<div class="block-header">
<h2>Delete</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<h3>Are You Sure You Want To Delete This?</h3>
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.ID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.ID)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.PatientBillID)
<br />
#Html.DisplayFor(model => model.billdetailmodel.PatientBillID)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Amount)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Amount)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedAt)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedAt)
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.CreatedBy)
<br />
#Html.DisplayFor(model => model.billdetailmodel.CreatedBy)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.DisplayNameFor(model => model.billdetailmodel.Description)
<br />
#Html.DisplayFor(model => model.billdetailmodel.Description)
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-actions no-color">
#Html.HiddenFor(model => model.billdetailmodel.ID)
<input type="submit" value="Delete" class="btn btn-default" /> |
#Html.ActionLink("Back to List", "EditBill")
</div>
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
I think there is problem with my controller logic how can I look for different ids passed in the Delete function and check in two different table and pass result to viewmodel?
Please tell me what I am doing wrong in it. Thanks in advance
You are actually returning returning wrong object to your View. You should be passing the DeleteViewModel object back to your View something like :
DeleteViewModel deleteViewModel = new DeleteViewModel ();
deleteViewModel.billmodell = billmodell;
deleteViewModel.billdetailmodel = billdetailmodell;
and then pass it in your View() method call:
return View(deleteViewModel);
Your code after loading records from db should be like:
DeleteViewModel deleteViewModel = new DeleteViewModel();
deleteViewModel.billmodell = new PatientsBillViewModel(); ;
deleteViewModel.billdetailmodel = new PatientsBillDetailViewModel();
tblPatientBill bill = db.tblPatientBills.Find(id);
tblPatientBillDetail billdetail = db.tblPatientBillDetails.Find(id);
if (bill != null)
{
deleteViewModel.billmodell.ID = bill.ID;
deleteViewModel.billmodell.PatientAppointmentID = bill.PatientAppointmentID;
deleteViewModel.billmodell.BillNo = bill.BillNo;
deleteViewModel.billmodell.Amount = bill.Amount;
deleteViewModel.billmodell.Discount = bill.Discount;
deleteViewModel.billmodell.CreatedAt = bill.CreatedAt;
deleteViewModel.billmodell.CreatedBy = bill.CreatedBy;
deleteViewModel.billmodell.Description = bill.Description;
}
if(billdetail != null)
{
deleteViewModel.billdetailmodel.ID = billdetail.ID;
deleteViewModel.billdetailmodel.PatientBillID = billdetail.PatientBillID;
deleteViewModel.billdetailmodel.Amount = billdetail.Amount;
deleteViewModel.billdetailmodel.CreatedAt = billdetail.CreatedAt;
deleteViewModel.billdetailmodel.CreatedBy = billdetail.CreatedBy;
deleteViewModel.billdetailmodel.Description = billdetail.Description;
}
return View(deleteViewModel);
I am trying to get a value from a textbox of my View.
This is my View:
#model MyDataIndexViewModel
#{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email})
</div>
</div>
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="btn btn-default pull-right" href="/ChangeMyData/Save">Speichern</a>
</div>
</div>
This is my Controller:
[HttpPost]
public ActionResult Save()
{
var email = Request["txtEmail"].ToString();
return View();
}
I get the error just as it says in the Title.
Thank you in advance!
VIEW:
#model MyDataIndexViewModel
#using (Html.BeginForm("Save", "CONTROLLER_NAME"))
{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email, id="txtEmail"})
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="submit btn btn-default pull-right">Speichern</a>
</div>
</div>
}
CONTROLLER
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
You can either use strongly-typed viewmodel binding:
View
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBox("txtEmail", Model.Email)
Controller
[HttpPost]
public ActionResult Save(MyDataIndexViewModel model)
{
var email = model.Email;
return View();
}
Or use a TextBoxFor directly for model binding:
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBoxFor(model => model.Email)
Or if you still want to use HttpRequest members, Request.Form collection (a NameValueCollection) is available to retrieve text from txtEmail input:
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
Note that Request["txtEmail"] is discouraged due to no compile time safety applied for it, because the key value may retrieved from Request.QueryString, Request.Form or other HttpRequestBase members.
Similar issue:
MVC TextBox with name specified not binding model on post
Access form data into controller using Request in ASP.NET MVC
There are some similar topics in forums, but there isn't any good answer. First question is that is it possible to pass httppostedfilebase to controller, when using modal popup?
When I am using regular model and view, then everything is working well, but as soon I make this view as partialview, then everything except file is passing to controller. File is getting null value.
List View where modalpopup is excecuting:
<button style="cursor:pointer" type="submit" class="fluent-big-button" onclick="ShowModal('#Url.Action("Create", "Device")')" >
Modal Popup View:
#using (Html.BeginForm("Create", "Device", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
<fieldset>
<legend>#Resources.Insert_New_Device</legend>
<div class="grid" style="margin: 0px auto">
<div class="row" style="margin: 0px auto">
<div class="span10">
<div class="row" style="margin: 0px auto">
<div style="white-space:nowrap" class="span2 readable-text"><label>#Resources.Device_No:</label> </div>
<div class="span3">
<div class="input-control text" data-role="input-control">
#Html.TextBoxFor(m => Model.No, new { required = "required", autofocus = "autofocus", #tabindex="1"})
#Html.ValidationMessageFor(m => Model.No)
<button tabindex="-1" class="btn-clear" type="button"></button>
</div>
</div>
<div style="white-space:nowrap" class="span2 readable-text"><label>Tootja:</label> </div>
<div class="span3">
<div class="input-control text" data-role="input-control">
#Html.TextBoxFor(m => Model.Manufacturer_Name, new { autofocus = "autofocus", #tabindex="2"})
#Html.ValidationMessageFor(m => Model.Manufacturer_Name)
<button tabindex="-1" class="btn-clear" type="button"></button>
</div>
</div>
</div>
<div class="row" style="margin: 0px auto">
<div style="white-space:nowrap" class="span2 readable-text"><label>Pilt:</label> </div>
<div class="span3">
<div class="fallback">
<input type="file" name="DeviceImage" id="DeviceImage" />
</div>
</div>
</div>
</div>
<div class="row" style="margin: 0px auto">
<div class="span10">#Html.ValidationMessage("CustomError")</div>
</div>
</div>
</div>
</fieldset>
</div>
</div>
<div class="modal-footer">
<div class="grid" style="margin: 0px auto">
<div class="row" style="margin: 0px auto">
<div class="span4"></div>
<div class="span3">
<button class="button large span3" data-dismiss="modal">Cancel</button>
</div>
<div class="span3">
<input class="large span3 success" type="submit" value="Ok" />
</div>
</div>
</div>
</div>
}
Controller:
public ActionResult Create()
{
ViewBag.exsistingDevices = GetExsistingDevices();
return PartialView("_Create");
}
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin, Super")]
public async Task<ActionResult> Create(Device device, HttpPostedFileBase DeviceImage)
{
try
{
if (ModelState.IsValid)
{
SPDBContext db = new SPDBContext();
device.Last_Action_Date = DateTime.Now;
// Insert image
if (DeviceImage != null)
{
if (DeviceImage.ContentLength > (2 * 1024 * 1024) && DeviceImage.ContentLength < 1)
{
ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
}
var contentType = DeviceImage.ContentType;
device.Image = new byte[DeviceImage.ContentLength];
DeviceImage.InputStream.Read(device.Image, 0, DeviceImage.ContentLength);
}
db.Devices.Add(device);
await db.SaveChangesAsync();
return Json(new { success = true });
}
}
catch (Exception e)
{
ModelState.AddModelError("CustomError", String.Format("{0}: {1}",Resources.Resources.Insert_Failed, e.Message));
}
return PartialView("_Create", device);
}
Model:
[NotMapped]
public HttpPostedFileBase DeviceImage { get; set; }
public byte[] Image { get; set; }