How do I insert multiple checkbox values into a database? - c#

I am using ASP.NET Core 3.1 MVC with C#, I want to insert multiple checkbox value into a column ItemName in my database table row. However, even when I selected more than one value, my database only successfully manages to add one value.
How do I insert more than one value into my database?
Here is my controller:
[AllowAnonymous]
[HttpPost]
public IActionResult AddPackage(Package pkg, IFormFile photo)
{
if (!ModelState.IsValid)
{
ViewData["Message"] = "Invalid Input";
ViewData["MsgType"] = "warning";
return View("AddPackage");
}
else
{
string picfilename = DoPhotoUpload(pkg.Photo);
List<string> itemmm = new List<string>();
IFormCollection form = HttpContext.Request.Form;
string itemm = form["ItemName"].ToString();
itemmm.Add(itemm);
itemmm = itemm.Split(',').ToList();
foreach (string itm in itemmm)
{
string sql = #"INSERT INTO Package(PackageName, PackageDesc, ItemName, Picture) VALUES('{0}', '{1}', '{2}', '{3}')";
string insert = String.Format(sql, pkg.PackageName.EscQuote(), pkg.PackageDesc.EscQuote(), itm.EscQuote(), picfilename);
if (DBUtl.ExecSQL(insert) == 1)
{
double payment = Calcforpackage(pkg);
TempData["Message"] = "Heath Package Added";
TempData["MsgType"] = "success";
return RedirectToAction("AdminPackage");
}
else
{
TempData["Message"] = "Package not found.";
TempData["MsgType"] = "warning";
return View();
}
}
return RedirectToAction("AdminPackage");
}
}
Here is my view:
<div class="form-group row">
<label class="offset-3 control-label col-2" >Select Items :</label>
<div class="col-3">
<div class="form-check form-check-inline " >
<li>
#foreach (TestItem row in ViewData["GetItem"] as List<TestItem>)
{
<input type="checkbox" class="form-check-input" id="#row.ItemId"
name="ItemName" value="#row.ItemName.ToString()" />
<label class="form-check-label" for="#row.ItemId">#row.ItemName.ToString() </label><br />
}
</li>
</div>
<div class="col-4">
<span asp-validation-for="ItemName" class="text-danger"></span>
</div>
</div>
</div>
Thank you for the help in advance!

Related

Filtering and Sorting in ASP.NET Core MVC

I am new to ASP.NET Core MVC, and I want to see if it ok to implement sorting and to filter this way. I have seen Microsoft tutorials about it, but I could not implement it like them.
The context will be changed later with View Model.
Index view:
#model ProductListVM
#{
}
<h2>All Products</h2>
<hr />
<form class="row form-inline" onsubmit="onSubmit()" asp-action="Index" method="get" id="productsForm">
<div class="col-sm-2">
<select class="form-select" asp-for="CategoryId" onchange="filterAndSortProducts()" asp-items="ViewBag.Categories" style="width: 100%;">
<option>Select Category</option>
</select>
</div>
<div class="col-sm-2">
<select asp-for="SortParam" onchange="filterAndSortProducts()" class="form-select" style="width: 100%;" asp-items="ViewBag.SortItems">
<option value="">Sort By</option>
</select>
</div>
<div class="col-sm-3">
<div class="input-group">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="SearchString" value="#ViewData["CurrentFilter"]" />
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit" onsubmit="onsubmit()">Search</button>
</div>
</div>
</form>
<hr />
<div class="row">
#foreach(var item in Model.Products) {
<div class="col-md-3 col-sm-6">
<div class="product-grid">
<div class="product-image">
<a href="#" class="image">
<img class="pic-1" src="~/images/#item.ImagePath">
</a>
#if(item.IsOnSale) {
<span class="product-sale-label">Sale!</span>
}
<ul class="product-links">
<li><i class="fa fa-shopping-bag"></i> Add to cart</li>
<li><i class="fa fa-search"></i>Quick View
</li>
</ul>
</div>
<div class="product-content">
<h3 class="title">#item.Name</h3>
<div class="price">#if (item.IsOnSale)
{
<span>$#item.Price</span>
} $#item.CurrentPrice</div>
</div>
</div>
</div>
}
</div>
<script>
function filterAndSortProducts(e) {
var form = document.getElementById("productsForm");
form.submit();
}
function onSubmit(e) {
e.preventDefault();
}
</script>
View Model:
namespace ECommerce.Common.Models
{
public class ProductListVM
{
public string? SortParam { get; set; }
public int CategoryId { get; set; }
public List<ProductVM>? Products { get; set; }
}
}
Controller, Index action:
public async Task<IActionResult> Index(string searchString, ProductListVM model)
{
var sortParam = model.SortParam;
var categoryFilterId = model.CategoryId;
ViewData["CurrentFilter"] = searchString;
var products = new List<Product>();
if (!string.IsNullOrEmpty(searchString))
{
products = await productRepository.GetAllWithSearchStringAsync(searchString);
}
else
{
products = await productRepository.GetAllAsync();
};
switch (sortParam)
{
case "price_desc":
products = products.OrderByDescending(s => s.Price).ToList();
break;
case "price_asc":
products = products.OrderBy(s => s.Price).ToList();
break;
case "date_desc":
products = products.OrderByDescending(s => s.DateCreated).ToList();
break;
case "date_asc":
products = products.OrderBy(s => s.DateCreated).ToList();
break;
default:
products = products.OrderBy(s => s.DateCreated).ToList();
break;
}
if(categoryFilterId != 0)
products = products.Where(q => q.ProductCategoryId == categoryFilterId).ToList();
ViewBag.SortItems = new List<SelectListItem>()
{
new SelectListItem() { Text = "Price: Highest to Lowest", Value = "price_desc"},
new SelectListItem() { Text = "Price: Lowest to Highest", Value = "price_asc"},
new SelectListItem() { Text = "Date: Newest to Oldest", Value = "date_desc"},
new SelectListItem() { Text = "Date: Oldest to Newest", Value = "date_asc"},
};
ViewBag.Categories = new SelectList(context.Categories, "Id", "Name");
model = new ProductListVM
{
Products = mapper.Map<List<ProductVM>>(products)
};
return View(model);
}
Dates also will be changed, it is just an example at the moment.
Any suggestion, critique, or tip is helpful. I am in learning progress.
I think your using EF and the productRepository is a DBContext. This gives you back a IEnumerable which is only evaluatet if you use the Data. My Tipp for you to call .ToList() just in the End. It makes a big difference in performance.
List<Product> products = productRepository.Products;
if (!string.IsNullOrEmpty(searchString))
{
products = await products.WhereAsync(p = p.Where(s => s.Name.Contains(searchString)));
}
if (categoryFilterId != 0)
{
products = products.Where(q => q.ProductCategoryId == categoryFilterId);
}
switch (model.SortParam)
{
case SortOrder.price_desc:
products = products.OrderByDescending(s => s.Price);
break;
case SortOrder.price_asc:
products = products.OrderBy(s => s.Price);
break;
case SortOrder.date_desc:
products = products.OrderByDescending(s => s.DateCreated);
break;
default:
products = products.OrderBy(s => s.DateCreated);
break;
}
I would also use a Enum for you SortParam.
public enum SortOrder
{
price_desc,
price_asc,
date_desc,
date_asc
}
Hope that helps

How do I refer the same button to different pages?

I am trying to refer the button order now to each different product I have in my table. What is the best possible way to deal with this kind of situation? At this moment all order now buttons refer to the first record of Product each time. But I am trying to get the data of each different column to the corresponding order now button. What is the best possible way to do this? Here you can find my corresponding Database Tables
Consoller:
public ActionResult PurchaseProduct()
{
if (Session["name"] == null)
{
return RedirectToAction("Index", "Customer");
}
var fetch = db.Products.FirstOrDefault();
Session["pid"] = fetch.P_id;
Session["pname"] = fetch.P_Name;
return View(db.Products.ToList());
}
[HttpPost]
public ActionResult Order(Product pt, Customer cr, int Quantity)
{
//available amount before order
Session["p_name"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_Name).SingleOrDefault();
Session["available_quantity"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_amount).SingleOrDefault();
//amount needed
Session["needed_quantity"] = Quantity;
int a = Convert.ToInt32(Session["needed_quantity"]);
int b = Convert.ToInt32(Session["available_quantity"]);
if ( a <= b )
{
ViewBag.Message = "Order placed.";
//quantity after the order has been placed
int final_quantity = b - a;
//total price (amount needed*price)
Session["total_price"] = db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_price).SingleOrDefault();
int total_price = Convert.ToInt32(Session["total_price"]) * a;
//amount after the order
Session["final_quantity"] = db.Products.Where(x => x.P_id == pt.P_id).Update(x => new Product { P_amount = final_quantity });
Session["c_id"] = db.Customers.Where(x => x.C_Id == cr.C_Id).Select(x => x.C_Id).SingleOrDefault();
int c_id = Convert.ToInt32(Session["c_id"]);
Session["p_id"]= db.Products.Where(x => x.P_id == pt.P_id).Select(x => x.P_id).SingleOrDefault();
int p_id = Convert.ToInt32(Session["p_id"]);
//adding record to table 'order'
string p_name = Session["p_name"].ToString();
Session["Add_Order"] = db.Orders.Add(new Order {O_name = p_name, O_Price = total_price
, O_amount = a ,C_id = c_id, P_id = p_id});
db.SaveChanges();
}
else
{
ViewBag.Message = "Order can't be placed, product amount is " + b.ToString();
}
return View();
}
Products overview page
#model IEnumerable<IMS.Models.Product>
#{
foreach (var item in Model)
{
<tr>
<td>#item.P_Name</td>
<td>#item.P_size</td>
<td>#item.P_price</td>
<td><img src="/images/#item.P_Image" width="200" height="200" /></td>
<td>Order Now</td>
</tr>
}
}
</table>
</div>
Page of each individual product after clicking order now
<div class="form-group">
#{
using (Html.BeginForm())
{
<p style="color:red;">#ViewBag.Message</p>
<div class="form-group">
<label>Product name: </label>
<input type="text" name="pname" id="pname" value="#Session["pname"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Customer id: </label>
<input type="text" name="c_id" id="c_id" value="#Session["id"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Product id: </label>
<input type="text" name="p_id" id="p_id" value="#Session["pid"]" class="form-control" readonly />
</div>
<div class="form-group">
<label>Amount: </label>
<label>Available amount: #Session["available_quantity"] </label>
<input type="text" name="Quantity" class="form-control" />
</div>
<input type="submit" value="Submit" name="submit" class="btn btn-success" />

How To Pass Submit Button Value To Controller Action Parameter?

I am trying to save data and edit that data using the button with Id btnSaveAnContinue. Now, whenever I click on Save And Continue button to save data, the command parameter in post method i.e gets Saveandcontinue which is defined in the button as per required.
But whenever, I try to edit the data and save it by clicking on same button, the command parameter in AddEdit POST method does not get Saveandcontinue, it is null.
The View:
<form asp-controller="Doctor" asp-action="AddEdit" method="post" class="form-horizontal" id="DoctorAddEdit" role="form">
#Html.HiddenFor(c => c.DoctorId)
<div class="m-b-md heading-tp-cls">
<h3 class="m-b-none pull-left">Doctor Information <small id="currentUsersInCase"></small></h3>
<div class="doc-buttons pull-right relative">
<button type="submit" class="btn btn-s-md btn-success saveButton" id="btnSave"><i class="fa fa-save fa-fw"></i>Save And Close</button>
<button type="submit" name="command" value="Saveandcontinue" id="btnSaveAnContinue" class="btn btn-s-md btn-success saveButton "><i class="fa fa-save fa-fw"></i>Save And Continue</button>
</div>
<div class="clearfix"></div>
</div>
<section class="panel panel-default tp-section-cls no-left-right-borders" style="padding-top: 10px;">
<div class="row m-l-none m-r-none bg-light lter">
<section>
<div class="col-lg-2 col-md-2 col-sm-6 error-holder-form hideSubject" id="claimanatFirstNameDiv">
<label>First Name<span class="requAstrik">*</span></label>
<input asp-for="FirstName" id="DFirstName" class="form-control subjectHide" placeholder="" type="text">
<span asp-validation-for="FirstName" class="text-danger error"></span>
</div>
<div class="col-lg-2 col-md-2 col-sm-6 hideSubject" id="claimanatMiddleInitialDiv">
<label>Middle Name</label>
<input asp-for="MiddleInitial" id="DMidName" class="form-control subjectHide" placeholder="" type="text">
</div>
</section>
</div>
</section>
</form>
GET method for AddEdit:
public IActionResult AddEdit(int id = 0, bool flag = false)
{
var getDoctorById = _doctorService.GetDoctorInfoById(id);
return View(getDoctorById);
}
POST method for AddEdit:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddEdit(DoctorInfoModel doctorInfo, string command)
{
bool isAjaxCall = HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (isAjaxCall)
{
return Content("Saved");
}
if (ModelState.IsValid)
{
var result = 0;
int userId = User.GetUserId();
doctorInfo.CreatedBy = userId;
var saveAndGetUserId = 0;
if (doctorInfo.DoctorId == 0)
{
saveAndGetUserId = _doctorService.SaveUserInfo(doctorInfo);
var user = new ApplicationUser { UserName = doctorInfo.UserName, Email = doctorInfo.DocEmail, UserId = saveAndGetUserId };
var getResult = await _userManager.CreateAsync(user, doctorInfo.Password);
_doctorService.SaveUserRole(user.Id);
}
else
{
var getUserId = _doctorService.GetUser(doctorInfo);
var user = _userManager.Users.FirstOrDefault(c => c.UserId == getUserId);
user.UserName = doctorInfo.UserName;
user.Email = doctorInfo.DocEmail;
if (doctorInfo.Password != null && !"Password#123".Equals(doctorInfo.Password))
{
user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, doctorInfo.Password);
}
try
{
var result1 = await _userManager.UpdateAsync(user);
}
catch (Exception ex)
{
throw;
}
}
var getSaveResult = _doctorService.SaveDoctor(doctorInfo, saveAndGetUserId);
if (getSaveResult.Id > 0)
{
Success(getSaveResult.MessageBody);
}
else
{
Warning(getSaveResult.MessageBody);
}
if (command == "Saveandcontinue")
{
return RedirectToAction(nameof(DoctorController.AddEdit), new { id = getSaveResult.Id, flag = true });
}
else
{
return RedirectToAction(nameof(HomeController.Index), "Doctor");
}
}
Warning("Failed to save Doctor, try again later.");
return View("AddEdit", doctorInfo);
}

How to insert json message in modal with asp.net mvc

I'm developing a system in .NET and I need to send a json controller msg to the view and show it in modal.
The user will import a spreadsheet and the spreadsheet will be inserted in the database, at the end of the modal it should appear with the message whether it was sent or not.
Or backend is already working.
 
I need help on the front because when I import, it loads a new page with
["Sent with success"]
(the messages are in portuguese) = ["Enviado com sucesso"]
Follows the controller code.
public JsonResult UploadExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = "C:/Users/70561/Documents";
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Planilha1$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "ExcelTable");
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Planilha1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var dados = from a in excelFile.Worksheet<RETORNO_CM>(sheetName) select a;
foreach (var a in dados)
{
try
{
if (a.CM_CODIGO != null && a.CM_QM_COMPONENTE_RMA != null && a.CM_NS != null && a.CM_DESCRICAO != null &&
a.CM_DEFEITO != null && a.J_FALHA != null &&
a.CM_TIPO_DEFEITO != null && a.J_PLACA_RETRABALHO != null &&
a.J_PLACA_RESTESTADA != null && a.J_STATUS != null && a.CM_NOME_TESTE != null && a.CM_NOME_DEBUG != null)
{
RETORNO_CM CM = new RETORNO_CM();
CM.CM_CODIGO = a.CM_CODIGO;
CM.CM_QM_COMPONENTE_RMA = a.CM_QM_COMPONENTE_RMA;
CM.CM_NS = a.CM_NS;
CM.CM_DESCRICAO = a.CM_DESCRICAO;
CM.CM_DATA_REPARO = a.CM_DATA_REPARO;
CM.CM_DEFEITO = a.CM_DEFEITO;
CM.J_FALHA = a.J_FALHA;
CM.CM_TIPO_DEFEITO = a.CM_TIPO_DEFEITO;
CM.CM_COMPONENTE = a.CM_COMPONENTE;
CM.J_PLACA_RETRABALHO = a.J_PLACA_RETRABALHO;
CM.J_PLACA_RESTESTADA = a.J_PLACA_RESTESTADA;
CM.J_STATUS = a.J_STATUS;
CM.CM_NOME_TESTE = a.CM_NOME_TESTE;
CM.CM_NOME_DEBUG = a.CM_NOME_DEBUG;
db.RETORNO_CM.Add(CM);
db.SaveChanges();
}
else
{
data.Add("<ul>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
//deleting excel file from folder
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
data.Add("Enviado com sucesso");
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
//alert message for invalid file format
data.Add("Apenas arquivos excel sao suportados");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
if (FileUpload == null) data.Add("Selecione um arquivo");
return Json(data, JsonRequestBehavior.AllowGet);
}
}
my view code
<div class="box">
<div class="box-body">
<hr />
<article class="table-responsive" style="overflow:hidden">
<p class="lead">Teste de importação.</p>
<hr />
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "return myFunction()" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enviar" id="btnSubmit" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>
<b>Message:</b><br>
<input class="message-edit-text" type="text" size="20">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</article>
</div>
You should not return JSON, as you are performing a full page postback. Instead, you should return a View.
If you do not want to perform a full page postback, you want to use Ajax since the beginning of the request.
For example,
View
Please make sure button is type="button" to avoid full page postback.
#using (Html.BeginForm("UploadExcel", "RetornoCM", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="form-group">
<div class="control-label col-md-2">Escolha o Arquivo:</div>
<div class="col-md-10">
<input type="file" id="FileUpload" name="FileUpload" class="" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" class="btn btn-primary">
Enviar
</button>
</div>
</div>
</div>
}
<script>
$(function () {
$('#btnSubmit').click(function() {
// Checking whether FormData is available in browser
if (window.FormData !== undefined) {
var fileUpload = $("#FileUpload").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '#Url.Action("UploadExcel", "RetornoCM")',
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function(result) {
alert(result);
},
error: function(err) {
alert(err.statusText);
}
});
}
});
});
</script>
Action Method
[HttpPost]
public ActionResult UploadExcel()
{
if (Request.Files.Count > 0)
{
try
{
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
// Do somethig with file
}
return Json("File Uploaded Successfully!");
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Source: File Upload Through JQuery AJAX In ASP.NET MVC

Why isn't my drop down value being submitted to the action?

I have a DropDownListFor on my view. In fact I have 3, out of three of them only two of them work. Despite being almost exactly the same code, my get around at the moment is to create an input box and populate it on click of a button with the value from the drop down box(strange I know, I can get the value using JQuery). I've checked and all names seem to be the same so I'm really not sure why it doesn't submit.
View:
<content id="GenerateReportContent" class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
#using (Html.BeginForm("ReportSelection", "Search", FormMethod.Post, new { #id = "GenerateReportContainer" })) {
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="AltFunctions">
<ul>
<li>
<a href="javascript:document.getElementById('GenerateReportContainer').reset();" class="AltButton" id="altClearButton" title="Reset the 'Generate Report' container" >Clear</a>
</li>
<li>
Info
</li>
</ul>
</div>
<h1 id="GenerateReportHeader">SEARCH ENGINE</h1>
</div>
<input type="hidden" name="ClientID" value="#Model.ClientID" id="Client" />
<input type="hidden" name="ClientName" value="#Model.ClientName" id="ClientName" />
<input type="hidden" name="SupplierFound" value="#Model.SupplierFound" id="SupplierFound" />
#Html.TextBoxFor(m => m.ClaimNo, "", new { #id = "txtGRCSelect", #class = "form-control", placeholder = "Enter Specific Claim Number..." })
<br />
<div class="ui-widget">
#Html.TextBox("SupplierAuto", "", new { #id = "SupplierAutotxt", #class = "form-control SupplierAutoComplete", placeholder = "Search for a supplier name" })
</div>
#Html.DropDownListFor(m => m.SupplierID, new SelectList(Model.Suppliers, "SupplierID", "DisplayName"), "Select Supplier Name", new { #id = "SuppNameDD", #class = "GRDropDown"})
<br />
<!-- THE DROP DOWN IN QUESTION-->
#Html.DropDownListFor(m => m.GroupModelClass.GroupID, new SelectList(Model.GroupModelClass.ClaimGroups, "GroupID", "GroupName"), "Select Supplier Group Name", new { #id = "SuppGroupDD", #class = "GRDropDown" })
<br />
#Html.DropDownListFor(m => m.ReviewPeriodID, new SelectList(Model.ReviewPeriods, "ReviewPeriodID", "ReviewPeriodName"), "Select Review Period", new { #id = "ReviewPeriodDD", #class = "GRDropDown" })
// Have to submit this field at the moment as the drop down value is not being submitted
<input hidden id="GroupIDInput" name="GroupIDInput" />
<br />
<br />
<button type="submit" value="Submit" id="GenerateReportButton" class="btn btn-default">GO</button>
<div id="ErrorBox" hidden>
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
<p id="ErrorBoxText"></p>
</div>
</div>
}
</content>
Controller:
public ActionResult ReportSelection(int ClientID, string ClaimNo, string SupplierAuto, int? SupplierID = null, int? ReviewPeriodID = null, int? GroupID = null) {
if (SupplierAuto != "") {
var Suppliers = suppRepo.GetAllSuppliersByClientWithClaims(ClientID);
foreach (var item in Suppliers) {
if (item.DisplayName == SupplierAuto) {
SupplierID = item.SupplierID;
break;
}
}
if (SupplierID == null) {
return RedirectToAction("Index", "Dashboard", new { ClientID = ClientID });
}
}
client = clientRepo.GetClientNameByID(ClientID);
if (SupplierID != null || ReviewPeriodID != null || GroupIDInput != null) {
return RedirectToAction("SupplierReportSelection", new { ClientID = ClientID, SupplierID = SupplierID, ReviewPeriodID = ReviewPeriodID, ClaimIDs = ClaimIDs });
}
else {
return RedirectToAction("ClaimNumberReportSelection", new { ClientID = ClientID, ClaimNo = ClaimNo });
}
}
Anyone know why it doesn't work?
Use FormCollection:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["<your-dropdown-name>"].ToString();
return View(MV);
}
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVender {get;set;}
}
and in View:
#Html.DropDownListFor(m=>m.SelectedVender , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
Check with fiddler or F12, but I'm betting m.GroupModelClass.GroupID is getting passed to the model binder as simply GroupID and it has no idea that it's supposed to map to GroupModelClass.GroupID. Try flattening your model a bit?

Categories