How to get the data-id Send to another controller mvc - c#

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');

Related

How to assign to each button his own calendar? asp.net MVC

I'm creating a web site, where I have a list of classes, and I want that each class will have it`s own calendar. What I mean is, when I click button 1, I will go to a separate calendar then button 2 and so on.
I already have a working calendar, I just don't understand how assign to each button a calendar.
So I have a working calendar with options of add/delete/update events, but I don't understand how to connect them.
I'm on this problem over a week now, and I couldn't find any solution. help please.
This is the index.cshtml where the classes are created: (classes view)
#model IEnumerable<ClasSaver.Models.ClassesModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<style>
.button {
background-color: deepskyblue; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Building)
</th>
<th>
#Html.DisplayNameFor(model => model.How_Many_In_Class)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Building)
</td>
<td>
#Html.DisplayFor(modelItem => item.How_Many_In_Class)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
<input id="#item.Id" type="button" onclick="parent.open('https://www.google.com/')" value="Open in new window" class="button">
</td>
</tr>
}
</table>
<script>
</script>
and the controller
using ClasSaver.Data;
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class ClassesController : Controller
{
// GET: Classes
public ActionResult Index()
{
List<ClassesModel> classes = new List<ClassesModel>();
ClassDAO classDao = new ClassDAO();
classes = classDao.FetchAll();
return View("Index",classes);
}
public ActionResult Details(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("Details", classes);
}
public ActionResult Create(ClassesModel classesModel)
{
return View("ClassesForm", classesModel);
}
[HttpPost]
public ActionResult ProcessCreate(ClassesModel classesModel)
{
//save to DB
ClassDAO classesDAO = new ClassDAO();
classesDAO.CreateOrUpdate(classesModel);
return View("Details", classesModel);
}
public ActionResult Edit(int id)
{
ClassDAO classesDAO = new ClassDAO();
ClassesModel classes = classesDAO.FetchOne(id);
return View("ClassesForm", classes);
}
public ActionResult Delete(int id)
{
ClassDAO classesDAO = new ClassDAO();
classesDAO.Delete(id);
List<ClassesModel> classes = classesDAO.FetchAll();
return View("Index", classes);
}
public ActionResult SearchForm()
{
return View("SearchForm");
}
[HttpPost]
public ActionResult searchForName(string searchPhrase)
{
ClassDAO classesDAO = new ClassDAO();
List<ClassesModel> searchResults = classesDAO.SearchForName(searchPhrase);
return View("Index", searchResults);
}
}
}
and this is where the calendar is created index.cshtml: (home view)
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Save Event</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function () {
var events = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
type: "GET",
url: "/home/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
eventID: v.EventID,
title: v.Subject,
description: v.Description,
start: moment(v.Start),
end: v.End != null ? moment(v.End) : null,
color: v.ThemeColor,
allDay: v.IsFullDay
});
})
GenerateCalender(events);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
$('#myModal #eventTitle').text(calEvent.title);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
$description.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
eventID: 0,
title: '',
description: '',
start: start,
end: end,
allDay: false,
color: ''
};
openAddEditForm();
$('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
EventID: event.eventID,
Subject: event.title,
Start: event.start.format('DD/MM/YYYY HH:mm A'),
End: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
ThemeColor: event.color,
IsFullDay: event.allDay
};
SaveEvent(data);
}
})
}
$('#btnEdit').click(function () {
//Open modal dialog for edit event
openAddEditForm();
})
$('#btnDelete').click(function () {
if (selectedEvent != null && confirm('Are you sure?')) {
$.ajax({
type: "POST",
url: '/home/DeleteEvent',
data: { 'eventID': selectedEvent.eventID },
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModal').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
$('#dtp1,#dtp2').datetimepicker({
format: 'DD/MM/YYYY HH:mm A'
});
$('#chkIsFullDay').change(function () {
if ($(this).is(':checked')) {
$('#divEndDate').hide();
}
else {
$('#divEndDate').show();
}
});
function openAddEditForm() {
if (selectedEvent != null) {
$('#hdEventID').val(selectedEvent.eventID);
$('#txtSubject').val(selectedEvent.title);
$('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
$('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
$('#chkIsFullDay').change();
$('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
$('#txtDescription').val(selectedEvent.description);
$('#ddThemeColor').val(selectedEvent.color);
}
$('#myModal').modal('hide');
$('#myModalSave').modal();
}
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
var data = {
Id: $('#hdEventID').val(),
Subject: $('#txtSubject').val().trim(),
Start: $('#txtStart').val().trim(),
End: $('#chkIsFullDay').is(':checked') ? null : $('#txtEnd').val().trim(),
Description: $('#txtDescription').val(),
ThemeColor: $('#ddThemeColor').val(),
IsFullDay: $('#chkIsFullDay').is(':checked')
}
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '/home/SaveEvent',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed');
}
})
}
})
</script>
}
and the controller
using ClasSaver.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ClasSaver.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetEvents()
{
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var events = dc.Events.ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
[HttpPost]
public JsonResult DeleteEvent(int eventID)
{
var status = false;
using (ClassaverDBEntities2 dc = new ClassaverDBEntities2())
{
var v = dc.Events.Where(a => a.EventID == eventID).FirstOrDefault();
if (v != null)
{
dc.Events.Remove(v);
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}

How to add specific user to table when you have many in one List in asp net core mvc

I have in one view two submit buttons
The First one search for users in Active directory
The Second one Add selected user to table AspNetUsers
I have specified username which is staff id in button attribute asp-route-id so that I can add that specific user from the list of users that will appear after clicking the search button. but the problem is that it add the first person in the list. it doesn't add the one I clicked on.
This is my controller
[AcceptVerbs("Get", "Post")]
public async Task<IActionResult> AddUser(SearchViewModel profile , string button, List<User> users )
{
if (button == "Search")
{
if (ModelState.IsValid)
{
users = new List<User>();
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.com"))
{
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.DisplayName = profile.Name + "*";
using (PrincipalSearcher srch = new PrincipalSearcher(qbeUser))
{
if (!string.IsNullOrEmpty(srch.FindAll().ToString()))
{
foreach (var found in srch.FindAll())
{
if (found != null)
{
users.Add(new User()
{
Name = found.Name,
Email = found.UserPrincipalName,
SatffID = found.SamAccountName
});
}
else
{
return View();
}
}
SearchViewModel returnmodel = new SearchViewModel(users);
return View(returnmodel);
}
}
}
}
}
if(button=="Add")
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email, DisplayName = profile.DisplayName };
var result = await userManager.CreateAsync(user);
if (result.Succeeded)
{
if(profile.Location !=null)
{
for (int i = 0; i < profile.Location.Count; i++)
{
var newUser = await userManager.FindByNameAsync(profile.ID);
var userId = newUser.Id;
//var newUser = profile.ID;
UserLocation userLoc = new UserLocation
{
UserID = userId.ToString(),
LocID = profile.Location[i]
};
userLocation.Add(userLoc);
}
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "No locs");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError(string.Empty, "");
}
return View(profile);
}
return View(profile);
}
This is my View AddUser
#model SearchViewModel
<h1>Add New User</h1>
#Html.ValidationSummary(true)
<form method="post" formaction="">
<div id="content">
<fieldset>
<div class="form-group col-md-12">
#Html.LabelFor(model => Model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { #class = "form-control", #style = "width:280px" }, })
</div>
<div>
<div class="form-group row">
<label asp-for="#Model.Location" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<select asp-for="#Model.Location" asp-items="Html.GetEnumSelectList<Location>()" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
<option value="">Please Select</option>
</select>
<span asp-validation-for="#Model.Location" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default" name="button" value="Search">
</div>
<div class="col-md-3">
</div>
</div>
</fieldset>
<br>
</div>
<table id="historyTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Staff Id</th>
<th>Add User</th>
</tr>
</thead>
<tbody>
#if (Model.FoundUsers != null)
{
#foreach (var user in Model.FoundUsers)
{
if (user != null)
{
<tr>
<td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="#user.Name" name="displayname" /></td>
<td><label asp-for="Email"></label><input asp-for="Email" value="#user.Email" name="Email" /></td>
<td><label asp-for="ID"></label><input asp-for="ID" value="#user.SatffID" name="ID" /></td>
<td><input type="submit" class="btn btn-primary" name="button" value="Add" asp-route-Id="#user.SatffID" asp-action="AddUser"></td>
</tr>
}
}
}
else
{
<tr>
<td colspan="4">No Record Available</td>
</tr>
}
</tbody>
</table>
</form>
}
#section Scripts{
<script>
$(document).ready(function () {
$('#Subjects_dropdown').multiselect();
});
</script>
}
I try to reproduce your issue in my side, and I found that if I click Add button, the request contains all rows data like screenshot below:
So I think the issue comes from the form submit, I tried to add form for each row, and it worked.
Here's my code snippet, just adding #using (Html.BeginForm()) for content。
Here's a similar question as yours, and you can also refer to it to write js script to achieve it.
My controller action:
[AcceptVerbs("Get", "Post")]
public IActionResult AddUser(SearchViewModel profile, string button, List<User> users)
{
ViewData["Location"] = new List<string> {
"location_a",
"location_b"
};
if (button == "Search")
{
if (ModelState.IsValid)
{
users = new List<User>();
users.Add(new User()
{
Name = "name_a",
Email = "email_a",
SatffID = "staff_a"
});
users.Add(
new User()
{
Name = "name_b",
Email = "email_b",
SatffID = "staff_b"
});
users.Add(
new User()
{
Name = "name_c",
Email = "email_c",
SatffID = "staff_c"
});
SearchViewModel returnmodel = new SearchViewModel();
returnmodel.FoundUsers = users;
return View(returnmodel);
}
}
if (button == "Add")
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = profile.ID, Email = profile.Email, DisplayName = profile.DisplayName };
//save data
return RedirectToAction("Index", "Home");
}
return View(profile);
}
return View(profile);
}
View code :
#model SearchViewModel
<h1>Add New User</h1>
#Html.ValidationSummary(true)
<form method="post" formaction="">
<div id="content">
<fieldset>
<div class="form-group col-md-12">
#Html.LabelFor(model => Model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(modelItem => Model.Name, new { htmlAttributes = new { #class = "form-control", #style = "width:280px" }, })
</div>
<div>
<div class="form-group row">
<label asp-for="#Model.Location" class="col-sm-2 col-form-label"></label>
<div class="col-sm-10">
<select asp-for="#Model.Location" asp-items="(#ViewData["Location"] as IEnumerable<SelectListItem>)" class="custom-select mr-sm-2" id="Subjects_dropdown" multiple>
<option value="">Please Select</option>
</select>
<span asp-validation-for="#Model.Location" class="text-danger"></span>
</div>
</div>
</div>
<div class="col-md-2">
<input type="submit" class="btn btn-default" name="button" value="Search">
</div>
<div class="col-md-3">
</div>
</div>
</fieldset>
<br>
</div>
<table id="historyTable" class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Staff Id</th>
<th>Add User</th>
</tr>
</thead>
<tbody>
#if (Model.FoundUsers != null)
{
#foreach (var user in Model.FoundUsers)
{
if (user != null)
{
<tr>
#using (Html.BeginForm())
{
<td><label asp-for="DisplayName"></label><input asp-for="DisplayName" value="#user.Name" name="displayname" /></td>
<td><label asp-for="Email"></label><input asp-for="Email" value="#user.Email" name="Email" /></td>
<td><label asp-for="ID"></label><input asp-for="ID" value="#user.SatffID" name="ID" /></td>
<td><input type="submit" class="btn btn-primary" name="button" value="Add" asp-route-Id="#user.SatffID" asp-action="AddUser"></td>
}
</tr>
}
}
}
else
{
<tr>
<td colspan="4">No Record Available</td>
</tr>
}
</tbody>
</table>
</form>
#section Scripts{
<script>
$(document).ready(function () {
$('#Subjects_dropdown').multiselect();
});
</script>
}
This is what related code I only added

jQuery ajax data return to json controller the value is null

I don't know why when jQuery ajax data is sent to the controller, value shows null, such as the picture shows success function (data) error. Get data empty。
When the code was first tested, only one data was null, but later it showed that all data values were null.
What part of the code am I having a problem with?
<script type="text/javascript">
$(document).ready(function () {
$("#table1").click('#SelectBtn', function () {
var bid = $(this).attr('data-id');
var status = $("#enumId option:selected").val();
var mess = $('#message-text').val();
$('#Submit').click('#enumId', function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("saveStatus")',
data: { id: bid, status:$("#enumId option:selected").val(), Remark:$('#message-text').val() },
success: function (data) {
bid.url(data);
status.val('');
mess.val('');
alert("Success, sent data to controller");
}, error: function (data) {
alert("Error: " + data);
},
})
})
})
})
</script>
public JsonResult saveStatus(int id, string status, string Remark)
{
int approvalId;
if (id == 0)
{
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();
approvalId = ap.Id;
}
else
{
approvalId = id;
}
Status stat = (Status)Enum.Parse(typeof(Status), status);
ApprovalStatus temp = new ApprovalStatus
{
Id = approvalId,
Remark = Remark,
Status = stat,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return Json(df);
}
<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>
<input type="hidden" value="#item.RequerForApprovalId" />
<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 data-rid="#item.ReimbursementId" class="btn btn-primary" id="Submit" >Submit</button>
<button class="btn btn-default" data-dismiss="modal" type="reset" id="Clear">Close</button>
</div>
</div>
</div>
</div>
</td>
</tr>
}
</table>
You need to make a viewmodel or a class to be able to bind those values in the controller.
// new model
public class JsonReceiveModel{
public int Id {get;set;}
public string Status {get;set;}
public string Remark {get;set;}
}
// modifed to use model.Id, model.Status, model.Remark
public JsonResult saveStatus(JsonReceiveModel model) {
int approvalId;
if (model.Id == 0) {
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();
approvalId = ap.Id;
} else {
approvalId = id;
}
Status stat = (Status) Enum.Parse(typeof(Status), status);
ApprovalStatus temp = new ApprovalStatus {
Id = approvalId,
Remark = model.Remark,
Status = model.Status,
AddDate = DateTime.Now
};
db.ApprovalStatuses.Add(temp);
db.SaveChanges();
var df = db.ApprovalStatuses.Where(s => s.Id == approvalId).ToList();
return Json(df);
}
Then include contentType: 'application/json' in your ajax call.
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("saveStatus")',
contentType: 'application/json',
data: {
id: bid,
status: $("#enumId option:selected").val(),
Remark: $('#message-text').val()
},
success: function(data) {
bid.url(data);
status.val('');
mess.val('');
alert("Success, sent data to controller");
},
error: function(data) {
alert("Error: " + data);
},
})

Duplicate Entity error when saving db even when the database is empty

I am making a MVC web app where one form affects many tables in the database. I have the page loading info into the Entity Framework, but I get a duplicate entity error when I run db.SaveChanges(). The database is completely empty so it has to be some error with the Save.
I suspect it has something to do with how I am uploading the data to the Framework, but I cannot figure out the correct way to do it.
Here is the Model:
public class BOGOModel
{
public BOGOModel()
{
}
public string PROMOTION_CODE { get; set; }
public string DESCRIPTION { get; set; }
public DateTime START_DATE_TIME { get; set; }
public DateTime END_DATE_TIME { get; set; }
public int[] BUY_MEMBERS { get; set; }
public int[] GET_MEMBERS { get; set; }
public int PERCENT_OFF { get; set; }
}
Here is the Controller:
public ActionResult BOGO()
{
return View();
}
[HttpPost]
public JsonResult BOGOSave(string MemberData)
{
BOGOModel ModelData = JsonConvert.DeserializeObject<BOGOModel>(MemberData);
PROMOTION Promotion = new PROMOTION();
Promotion.PROMOTION_CODE = ModelData.PROMOTION_CODE;
Promotion.DESCRIPTION = ModelData.DESCRIPTION;
Promotion.PROMOTION_TYPESysID = 12001;
Promotion.PROMOTION_APPLY_ASSysID = 98401;
Promotion.START_DATE_TIME = ModelData.START_DATE_TIME.ToString();
Promotion.END_DATE_TIME = ModelData.END_DATE_TIME.ToString();
db.PROMOTIONs.Add(Promotion);
AT_PROMOTION_ORG_UNIT PromotionOrgUnit = new AT_PROMOTION_ORG_UNIT();
PromotionOrgUnit.ORG_UNIT = "150";
PromotionOrgUnit.ORG_UNIT_TYPE = "Outlet";
PromotionOrgUnit.PARENT_ORG_UNIT = "DG";
db.AT_PROMOTION_ORG_UNIT.Add(PromotionOrgUnit);
ALLOCATED_ORG_UNIT AllocatedOrgUnit = new ALLOCATED_ORG_UNIT();
AllocatedOrgUnit.AT_PROMOTION_ORG_UNIT = PromotionOrgUnit;
db.ALLOCATED_ORG_UNIT.Add(AllocatedOrgUnit);
MP_PROMOTION__ALLOCATED_ORG_UNIT Map_P_A = new MP_PROMOTION__ALLOCATED_ORG_UNIT();
Map_P_A.PROMOTION = Promotion;
Map_P_A.ALLOCATED_ORG_UNIT = AllocatedOrgUnit;
db.MP_PROMOTION__ALLOCATED_ORG_UNIT.Add(Map_P_A);
PROMOTION_RULE BuyRule = new PROMOTION_RULE();
BuyRule.TARGET_TYPESysID = 1;
BuyRule.TARGET = 1;
db.PROMOTION_RULE.Add(BuyRule);
AT_PROMOTION_SET BuySetAttributes = new AT_PROMOTION_SET();
BuySetAttributes.name = "Buy";
BuySetAttributes.type = "BENEFIT";
BuySetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(BuySetAttributes);
PROMOTION_SET BuySet = new PROMOTION_SET();
BuySet.AT_PROMOTION_SET = BuySetAttributes;
db.PROMOTION_SET.Add(BuySet);
foreach(int upc in ModelData.BUY_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = BuySet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
PROMOTION_RULE GetRule = new PROMOTION_RULE();
GetRule.TARGET_TYPESysID = 1;
GetRule.TARGET = 1;
GetRule.BENEFIT_TYPESysID = 5;
GetRule.BENEFIT = ModelData.PERCENT_OFF;
db.PROMOTION_RULE.Add(GetRule);
AT_PROMOTION_SET GetSetAttributes = new AT_PROMOTION_SET();
GetSetAttributes.name = "Get";
GetSetAttributes.type = "TARGET";
GetSetAttributes.PROMOTION_SELECTIONSysID = 1;
db.AT_PROMOTION_SET.Add(GetSetAttributes);
PROMOTION_SET GetSet = new PROMOTION_SET();
GetSet.AT_PROMOTION_SET = GetSetAttributes;
db.PROMOTION_SET.Add(GetSet);
foreach (int upc in ModelData.GET_MEMBERS)
{
AT_PROMOTION_MEMBER_KEY_VALUE MemberValue = new AT_PROMOTION_MEMBER_KEY_VALUE();
MemberValue.KEY_VALUE = upc;
db.AT_PROMOTION_MEMBER_KEY_VALUE.Add(MemberValue);
PROMOTION_MEMBER Member = new PROMOTION_MEMBER();
Member.LK_KEY_TYPE = db.LK_KEY_TYPE.Where(Type => Type.KEY_TYPESysID == 1).First();
Member.AT_PROMOTION_MEMBER_KEY_VALUE = MemberValue;
db.PROMOTION_MEMBER.Add(Member);
MP_PROMOTION_SET__PROMOTION_MEMBER Map_S_M = new MP_PROMOTION_SET__PROMOTION_MEMBER();
Map_S_M.PROMOTION_SET = GetSet;
Map_S_M.PROMOTION_MEMBER = Member;
db.MP_PROMOTION_SET__PROMOTION_MEMBER.Add(Map_S_M);
}
MP_PROMOTION__PROMOTION_SET Buy_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Buy_Map_P_S.PROMOTION = Promotion;
Buy_Map_P_S.PROMOTION_SET = BuySet;
db.MP_PROMOTION__PROMOTION_SET.Add(Buy_Map_P_S);
MP_PROMOTION__PROMOTION_SET Get_Map_P_S = new MP_PROMOTION__PROMOTION_SET();
Get_Map_P_S.PROMOTION = Promotion;
Get_Map_P_S.PROMOTION_SET = GetSet;
db.MP_PROMOTION__PROMOTION_SET.Add(Get_Map_P_S);
db.SaveChanges();
return Json("success");
}
Here is the View:
#model Promotion_Generator.Models.BOGOModel
#{
ViewBag.Title = "Buy One Get One";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2><b>Buy One Get One Free</b></h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<p class = "control-label col-md-2"><b>Promotion Code</b></p>
<div class="col-md-10 PC">
<input type="text" name="f-Promotion-Code" class="form-control f-Promotion-Code01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Description</b></p>
<div class="col-md-10 Desc">
<input type="text" name="f-Description" class="form-control f-Description01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Start Date Time</b></p>
<div class="col-md-10 SDT">
<input type="datetime" name="f-Start-Date-Time" class="form-control f-Start-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>End Date Time</b></p>
<div class="col-md-10 EDT">
<input type="datetime" name="f-End-Date-Time" class="form-control f-End-Date-Time01" />
</div>
</div>
<div class="form-group">
<p class="control-label col-md-2"><b>Percent Off</b></p>
<div class="col-md-10 PO">
<input type="number" name="f-Percent-Off" class="form-control f-Percent-Off01" />
</div>
</div>
<div class="form-group col-md-10">
<h3><b>Buy Products</b></h3>
<table class="table" id="buytable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-buy">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classBuyAdd">Add More</button>
</div>
<div class="form-group col-md-10">
<h3><b>Get Products</b></h3>
<table class="table" id="gettable">
<thead>
<tr>
<th>Product UPC</th>
<th />
<th />
</tr>
</thead>
<tbody>
<tr class="data-get">
<td>
<input type="number" name="f-upc" class="form-control f-upc01" />
</td>
</tr>
</tbody>
</table>
<button type="button" id="btnAdd" class="btn btn-primary btn-md pull-right btn-sm classGetAdd">Add More</button>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" id="btnSubmit" value="Submit" class="btn btn-default">Submit</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to Home", "Index", "Home")
</div>
#section scripts{
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".classBuyAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-buy">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#buytable').append(contactdiv);
});
});
$(document).ready(function () {
$(document).on("click", ".classGetAdd", function () {
var rowCount = $('.data-contact-person').length + 1;
var contactdiv = '<tr class="data-get">' +
'<td><input type="number" name="f-upc' + rowCount + '" class="form-control f-upc01" /></td>' +
'<td><button type="button" id="btnDelete" class="deleteContact btn btn btn-danger btn-xs">Remove</button></td>' +
'</tr>';
$('#gettable').append(contactdiv);
});
});
$(document).on("click", ".deleteContact", function () {
$(this).closest("tr").remove();
});
function getAllData() {
var data = [];
$('div.PC').each(function () {
var upc = $(this).find('.f-Promotion-Code01').val();
data.push(upc);
});
$('div.Desc').each(function () {
var upc = $(this).find('.f-Description01').val();
data.push(upc);
});
$('div.SDT').each(function () {
var upc = $(this).find('.f-Start-Date-Time01').val();
data.push(upc);
});
$('div.EDT').each(function () {
var upc = $(this).find('.f-End-Date-Time01').val();
data.push(upc);
});
var UPC1 = []
$('tr.data-buy').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC1.push(upc);
});
var UPC2 = [];
$('tr.data-get').each(function () {
var upc = $(this).find('.f-upc01').val();
UPC2.push(upc);
});
$('div.PO').each(function () {
var upc = $(this).find('.f-Percent-Off01').val();
data.push(upc);
});
var alldata = {
'PROMOTION_CODE': data[0],
'DESCRIPTION': data[1],
'START_DATE_TIME': data[2],
'END_DATE_TIME': data[3],
'BUY_MEMBERS': UPC1,
'GET_MEMBERS': UPC2,
'PERCENT_OFF': data[4],
}
console.log(alldata);
return alldata;
}
$("#btnSubmit").click(function () {
var data = JSON.stringify(getAllData());
console.log(data);
$.ajax({
url: 'BOGOSave',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'MemberData': data }),
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
});
</script>
}
Any help would be appreciated. Thanks!
Edit 1: Here is the specific error message:
{"Violation of PRIMARY KEY constraint 'PK__AT_PROMO__36BD5C21B6ADDCDF'. Cannot insert duplicate key in object 'dbo.AT_PROMOTION_MEMBER_KEY_VALUE'. The duplicate key value is (0).\r\nThe statement has been terminated."}
The schema is way to large to fit in this post, but here is the table mentioned in the error:
CREATE TABLE [AT_PROMOTION_MEMBER_KEY_VALUE] (
[PROMOTION_MEMBER_KEY_VALUESysID] int PRIMARY KEY NOT NULL,
[KEY_VALUE] bigint NOT NULL,
[sku] varchar(MAX) NULL,
[owner] varchar(10) NULL,
[owner_type] int FOREIGN KEY REFERENCES [LK_OWNER_TYPE] ([OWNER_TYPESysID]) NULL,
[product_group_type] varchar(10) NULL
);
OK, I fixed the problem. It turns out that I didn't auto increment the primary key and since I wasn't manually setting it either it was always 0. Even though there wasn't anything in the database it still couldn't insert because I was trying to create two items and they had the same ID. Thanks to the comments that helped to figure this out.

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