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

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();
}
}
}

Related

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

Datatype DateTime doesn't show Time

I have problem regarding showing correct time in IndexPage. When I create Patient I want to be display DateTime, currently It is only represent Date but in Index Page I get time.
What I try so far is to add DataAnnotation in my Model something like:
public class AdmissionPacients
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Date and Time")]
//[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
//[DataType(DataType.Date)]
public DateTime DateAndTime { get; set; }
[Required]
[Display(Name = "Emergency Admission")]
public bool Emergency { get; set; }
public string Image { get; set; }
// Doctor
[Display(Name = "Doctor Name")]
public int DoctorId { get; set; }
[ForeignKey("DoctorId")]
public virtual Doctor Doctor { get; set; }
//Patient
[Display(Name = "Patient Name")]
public int PatientId { get; set; }
[ForeignKey("PatientId")]
public virtual Patient Patient { get; set; }
}
Create.cshtml
#model BergClinics.Models.ViewModel.AdmisionVM
#{
ViewData["Title"] = "Upsert";
var title = "Create Admission Patient";
}
<form method="post" enctype="multipart/form-data">
#if (Model.AdmissionPatient.Id != 0)
{
<input asp-for="AdmissionPatient.Id" hidden />
title = "Edit Admission Patient";
}
<div class="border p-3">
<div class="form-group row">
<h2 class="text-info pl-3">#title</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row py-2">
<div class="col-4">
<label>Doctor Full Name : </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.DoctorId" asp-items="#Model.DoctorSelectList" class="form-control">
<option disabled selected>--Select Docotor--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Full Name: </label>
</div>
<div class="col-8">
<select asp-for="AdmissionPatient.PatientId" asp-items="#Model.PatientSelectList" class="form-control">
<option disabled selected>--Select Patient--</option>
</select>
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Date and Time :</label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.DateAndTime" type="text" class="form-control datepicker">
</div>
</div>
#*<div class="form-group row py-2">
<div class="col-4">
<label asp-for="AdmissionPatient.DateAndTime"></label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.DateAndTime" class="form-control datepicker" />
<span asp-validation-for="AdmissionPatient.DateAndTime" class="text-danger"></span>
</div>
</div>*#
<div class="form-group row py-2">
<div class="col-4">
<label>Patient Image :</label>
</div>
<div class="col-3">
<input type="file" name="files" id="imageBox" multiple class="form-control" />
</div>
</div>
<div class="form-group row py-2">
<div class="col-4">
<label>Emergency reception :</label>
</div>
<div class="col-8">
<input asp-for="AdmissionPatient.Emergency" type="checkbox" class="form-control" id="emergencyId">
<label class="form-check-label" for="exampleCheck1"></label>
</div>
</div>
<div class="form-group row py-2">
<div class="col-8 offset-4 row">
<div class="col">
#if (Model.AdmissionPatient.Id != 0)
{
//update
<input type="submit" class="btn btn-info w-100" value="Update" />
}
else
{
//create
<input type="submit" onclick="return validateInput()" class="btn btn-primary w-100" value="Create" />
}
</div>
</div>
</div>
</div>
<div class="col-4">
#if (Model.AdmissionPatient.Id != 0)
{
<img src="#Constans.imagePath#Model.AdmissionPatient.Image" width="100%" style="border-radius:5px; border:1px solid #bbb" />
}
</div>
</div>
</div>
</form>
#section Scripts{
#{
<partial name="_ValidationScriptsPartial" />
}
<script src="~/js/admissionPatient.js"></script>
}
Index
<div class="container p-3 bg-white">
<div class="row pt-4">
<div class="col-6">
<h2 class="text-primary">Admission Patient List</h2>
</div>
<div class="col-6 text-right">
<a asp-action="Upsert" class="btn btn-primary">
<i class="fas fa-plus"></i> Create New Doctor
</a>
</div>
</div>
<br /><br />
#*<form asp-action="Index">
<p>
Date From: <input type="datetime" name="search" />
Date To: <input type="datetime" name="search">
<input type="submit" value="Search" />
</p>
</form>*#
#if (Model.Count() > 0)
{
<table id="tblData" class="table table-striped border" style="width:100%">
<thead>
<tr class="table-dark">
<th>
Doctor Full Name - CODE
</th>
<th>
Patient Full Name
</th>
<th>
Date and Time
</th>
<th>
Emergency
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var obj in Model)
{
<tr>
<td width="25%">#obj.Doctor.Firstname #obj.Doctor.Lastname #obj.Doctor.Code</td>
<td width="25%">#obj.Patient.FirstName #obj.Patient.LastName</td>
<td width="25%">#obj.DateAndTime</td>
#if (obj.Emergency == true)
{
<td width="25%" class="blink_me"><span class="blink_me">Emergency</span></td>
}
else
{
<td width="25%"><span class="text-info">#obj.Emergency</span></td>
}
<td class="text-center">
<div class="w-75 btn-group" role="group">
<a asp-route-Id="#obj.Id" asp-action="Upsert" class="btn btn-primary mx-2">
<i class="fas fa-edit"></i>
</a>
<a asp-route-Id="#obj.Id" asp-action="Delete" class="btn btn-danger mx-2">
<i class="far fa-trash-alt"></i>
</a>
</div>
</td>
</tr>
}
</tbody>
</table>
}
else
{
<p> No Admission Patient exists.</p>
}
</div>
#section Scripts{
<script src="~/js/admissionPatient.js"></script>
}
Controller
public class AdmissionPatientController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
public AdmissionPatientController(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult Index(string search)
{
IEnumerable<AdmissionPacients> admissionPatient = _db.AdmissionPacients
.Include(u => u.Patient)
.Include(d => d.Doctor);
if (!string.IsNullOrEmpty(search))
{
if (DateTime.TryParse(search, out var dateTime))
{
admissionPatient = admissionPatient.Where
(x => x.DateAndTime.ToShortDateString().Equals(dateTime.ToShortDateString())).ToList();
}
}
return View(admissionPatient);
}
//UPSERT GET
//UPdate and insERT
public IActionResult Upsert(int? Id)
{
AdmisionVM admissionVM = new AdmisionVM
{
AdmissionPatient = new AdmissionPacients(),
PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
}),
DoctorSelectList = _db.Doctors.Select(i => new SelectListItem
{
Text = i.Firstname + i.Lastname,
Value = i.Id.ToString()
})
};
AdmissionPacients admissionPatient = new AdmissionPacients();
if (Id == null)
{
// this is for create
return View(admissionVM);
}
else
{
// this is for edit
admissionVM.AdmissionPatient = _db.AdmissionPacients.Find(Id);
if (admissionVM.AdmissionPatient == null)
{
return NotFound();
}
return View(admissionVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(AdmisionVM admissionVM)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
string webRootPath = _webHostEnvironment.WebRootPath;
if (admissionVM.AdmissionPatient.Id == 0)
{
//Creating
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
_db.AdmissionPacients.Add(admissionVM.AdmissionPatient);
}
else
{
//Updating
var objFromDb = _db.AdmissionPacients.AsNoTracking().FirstOrDefault(u => u.Id == admissionVM.AdmissionPatient.Id);
if (files.Count > 0)
{
string upload = webRootPath + Constans.imagePath;
string fileName = Guid.NewGuid().ToString();
string extension = Path.GetExtension(files[0].FileName);
var oldFile = Path.Combine(upload, objFromDb.Image);
if (System.IO.File.Exists(oldFile))
{
System.IO.File.Delete(oldFile);
}
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extension), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
admissionVM.AdmissionPatient.Image = fileName + extension;
}
else
{
admissionVM.AdmissionPatient.Image = objFromDb.Image;
}
_db.AdmissionPacients.Update(admissionVM.AdmissionPatient);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
admissionVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
admissionVM.DoctorSelectList = _db.Doctors.Select(i => new SelectListItem
{
Text = i.Firstname + i.Lastname,
Value = i.Id.ToString()
});
return View(admissionVM);
}
//GET - DELETE
public IActionResult Delete(int? id)
{
if (id == null || id == 0)
{
return NotFound();
}
AdmissionPacients admissionPatient = _db.AdmissionPacients
.Include(u => u.Patient)
.Include(d => d.Doctor)
.FirstOrDefault(u => u.Id == id);
if (admissionPatient == null)
{
return NotFound();
}
return View(admissionPatient);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeleteAdmission(int? Id)
{
var obj = _db.AdmissionPacients.Find(Id);
if (obj == null)
{
return NotFound();
}
string upload = _webHostEnvironment.WebRootPath + Constans.imagePath;
var oldfile = Path.Combine(upload, obj.Image);
if (System.IO.File.Exists(oldfile))
{
System.IO.File.Delete(oldfile);
}
_db.AdmissionPacients.Remove(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
Nothing works!
So I want as user to be able to select DateTime and this DateTime needs to be represent in IndexPage
Anyone know where did I make mistake ? What I made wrong here ?
I think you should use DateTime.ToString() formatting. There are many formats of datetimes are available in C# . Please check the link => DateTime Formatting Link
DateTime DateAndTime = new DateTime(2020, 5, 29, 5, 50, 0);
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 05:50
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 05:50 AM
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 5:50
DateAndTime.ToString("dddd, dd MMMM yyyy");//Output:Friday, 29 May 2020 5:50 AM
DateAndTime.ToString("dddd, dd MMMM yyyy HH:mm:ss");//Output:Friday, 29 May 2020 05:50:06
DateAndTime.ToString("MM/dd/yyyy HH:mm");//Output:05/29/2020 05:50
DateAndTime.ToString("MM/dd/yyyy hh:mm tt");//Output:05/29/2020 05:50 AM
DateAndTime.ToString("MM/dd/yyyy H:mm");//Output:05/29/2020 5:50
DateAndTime.ToString("MM/dd/yyyy h:mm tt");//Output:05/29/2020 5:50 AM
DateAndTime.ToString("MM/dd/yyyy HH:mm:ss");//Output:05/29/2020 05:50:06
Note: Here Outputs are dummy data output. Please check your code with "ToString" and let me know.
OR
You can use Annotation too like=>
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-ddTHH:mm:ss}")]`
OR
You can also check that link to on stackoverflow. Link

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

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

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.

Categories