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" />
Related
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
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!
How to get the data-id sent to another controller in ASP.NET MVC?
The employee submits the form, automatically determines the id and department position, and then sends it to the manager for approval.
The manager clicks approval or reject on this page, and the form is sent to the next person for approval. At this step, the page prompts that id = null cannot be run. What should I do?
But Google background shows that I got this Id, how to send this Id to action?
public PartialViewResult saveStatus(int id, string Status, string AddDate, string Remark)
{
int approvalId;
if (id == 0 && Session["AppId"] == null)
{
var staff = db.Staffs.Where(s => s.UserName == User.Identity.Name).FirstOrDefault();
RequestForApproval ap = new RequestForApproval
{
RequestToStaffId = staff.Id,
RequestDate = DateTime.Now,
};
db.RequestForApprovals.Add(ap);
db.SaveChanges();
Session["AppId"] = ap.ReimbursementID;
approvalId = ap.Id;
}
else
{
approvalId = int.Parse(Session["AppId"].ToString());
}
ApprovalStatus temp = new ApprovalStatus
{
Id = approvalId,
Remark = Remark,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return PartialView(df);
}
public JsonResult CreateStatus()
{
List<ApprovalStatus> mv = new List<ApprovalStatus>();
if(Session["AppId"] == null)
{
ViewBag.Ae = 0;
}
else
{
ViewBag.Ae = Session["AppId"];
int approvalId = int.Parse(Session["AppId"].ToString());
mv = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
}
return Json(mv);
}
public ActionResult AddRequestForApproval()
{
// var staffUser = db.StaffPositions.Where(a => a.Staff.UserName == System.Web.HttpContext.Current.User.Identity.GetUserId());
var rmid = Session["RmId"].ToString();
if (string.IsNullOrEmpty(rmid))
{
return RedirectToAction("Index");
}
int reimbursementId = int.Parse(rmid);
Session["RmId"] = null;
var Res = db.Reimbursements.Find(reimbursementId);
var managerId = GetByStaffId(Res.StaffId,reimbursementId);
RequestForApproval temp = new RequestForApproval();
temp.ReimbursementID = reimbursementId;
temp.RequestDate = DateTime.Now;
temp.RequestToStaffId = managerId;
db.RequestForApprovals.Add(temp);
db.SaveChanges();
return RedirectToAction("Index");
}
View:
#model Reimbursements.Models.RequesViewModel
#{
ViewBag.Title = "Index";
var add = Session["AppId"];
}
<h2>Index</h2>
<table class="table" id="table1">
<tr>
<th></th>
<th>
Staff Fname
</th>
<th>
RequestDate
</th>
<th></th>
</tr>
#foreach (var item in Model.GetReApproval)
{
<tr>
<td>
#item.ReimbursementId
</td>
<td>
#item.StaffName
</td>
<td>
#item.RequestDate
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-id="#item.RequerForApprovalId" data-target="#exampleModal" id="SelectBtn">Select</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="Title">Select and Confirm</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group" >
<input type="hidden" id="Reid" />
#Html.DropDownList("ApprovalStatus", null, new { #class = "btn btn-info",id="enumId" })
#*#Html.DropDownList("Index", ViewBag.DropDownList as SelectList,null, new { #class = "btn btn-info",#id="DropDownList" })*#
</div>
<hr />
<div class="form-group" style="visibility:visible" id="remarktext">
<label for="message-text" class="control-label">Remark:</label>
<textarea class="form-control" id="message-text" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
#*<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Confirme</button>*#
<button data-id="#item.ReimbursementId" class="btn btn-primary" id="Submit" #*onclick="location.href='#Url.Action("AddRequestForApproval","Reimbursements")'"*#>Submit</button>
<button class="btn btn-default" data-dismiss="modal" type="reset" id="Clear">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
#section Scripts {
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#table1").on('click', '#SelectBtn', function () {
$('#Submit').click('#enumId', function () {
var bid = $(this).attr('data-id');
var status = $("#enumId option:selected").val();
var mess = $('#message-text').val();
var Rmid;
console.log(bid, status, mess);
// var b = $("#NewId");
#*if ($("#NewId").val() == undefined) {
Rmid = 0;
} else {
Rmid = $("#NewId").val();
}
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("saveStatus")',
data: { id: bid, status: status, Remark: mess },
success: function (data) {
console.log(data);
status.val('').url(data);
mess.val('');
}, error: function (data) {
alert("error");
},
})*#
})
})
})
</script>
}
Instead of putting data-id there, you can just put it as value of a hidden filed in your form so that it gets posted when the form submitted:
<input type = "hidden" name="id" value="#item.ReimbursementId" />
If the value may change that you want to send different values when different buttons are clicked, then you can have a hidden input and set its value before submit:
$('#Submit').click('#enumId', function () {
var bid = $(this).data('id');
$('[name="id"]').val(bid);
// rest of your code....
});
Edit: if you are going to post it with ajax, please note that you should get data like:
$(this).data('id');
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);
}
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?