Stored procedures returning null value in razor pages - stored-procedures

I have two stored procedures which will execute based on a condition.
First stored procedure : AvailableHourSlots:
CREATE PROCEDURE [dbo].[AvailableHourSlots]
#ActivityName nvarchar(max) ,
#BookedDate datetime2(7)
AS
SELECT DISTINCT HourlyBasedTime
FROM ManageBooking AS mb, HourlyBased AS hb
WHERE bookingdate = #BookedDate
AND ActivityName = #ActivityName
AND (SUBSTRING(HourlyBasedTime, 1, 2) <> SUBSTRING(mb.PreferredTimeslot, 1, 2))
Second stored procedure : AvailableHalfAnHourSlots:
CREATE PROCEDURE [dbo].[AvailableHalfAnHourSlots]
#ActivityName nvarchar(max) ,
#BookedDate datetime2(7)
AS
SELECT DISTINCT hh.halfanhourtime
FROM ManageBooking AS mb, Halfanhour hh
WHERE bookingdate = #BookedDate
AND ActivityName = #ActivityName
AND (SUBSTRING(hh.halfanhourtime, 1, 5) <> SUBSTRING(mb.PreferredTimeslot, 1, 5))
AND (RIGHT(hh.halfanhourtime, 5) <> RIGHT(mb.PreferredTimeslot, 5))
Model created based on the first stored procedure output:
namespace ActivityBookingSystem.Models
{
public class HourlyBasedView
{
public string HourlyBasedTime { get; set; }
}
}
ApplicationDbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<NonOperatingDaysView>().HasNoKey();
modelBuilder.Entity<AvailableOneHourSlots>().HasNoKey();
modelBuilder.Entity<HourlyBasedView>().HasNoKey();
//modelBuilder.Ignore<HourlyBasedView>(); //ignore create the table for the stored procedure
//modelBuilder.Query<HourlyBasedView>();
}
public DbSet<ActivityBookingSystem.Models.HourlyBasedView> HourlyBasedView { get; set; }
create.cshtml - Ajax call:
function GetAvailableSlots(e) {
var rootPath = '#Url.Content("~")';
alert("Hi");
var ActivityList = document.getElementById("DrpDwnActivityList");
var ActivityListValue = ActivityList.options[ActivityList.selectedIndex].value;
var BookedDate = document.getElementById("DateBookedDate").value;
$.ajax({
type: "Get",
url: rootPath + "/ManageBooking/Create?handler=GetAvailableSlots",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: { Duration: e.value,ActivityName:ActivityListValue,BookedDate:BookedDate },
dataType: "json",
success: function (result) {
//console.log(result), //just for debug
// $("#TrainingType").val(result.trainingType), //mind this should be lower-case letters by default setting
// $("#TrainingVersion").val(result.version),
// $("#SessionType").val(result.sessionType)
alert(result);
},
error: function (data) {
alert(data);
}
});
}
create.cshtml.cs:
public async Task<JsonResult> OnGetGetAvailableSlotsAsync(string ActivityName, string BookedDate, string Duration)
{
Console.WriteLine(Duration);
DateTime BookingDate = Convert.ToDateTime(BookedDate);
ActivityName = ActivityName.ToString();
if (Duration == "1 Hour")
{
var LstPreferredTimeSlot = _context.HourlyBasedView.FromSqlRaw("EXEC dbo.AvailableHourSlots #BookingDate = {0}, #ActivityName = {1}", BookingDate, ActivityName)
.AsNoTracking().ToList();
// var PreferredTimeSlot = await _context.HourlyBasedView.FromSqlRaw($"SELECT distinct HourlyBasedTime FROM ManageBooking as mb, HourlyBased as hb WHERE bookingdate = {BookingDate} and ActivityName = {ActivityName} and (substring(HourlyBasedTime,1,2) <> substring(mb.PreferredTimeslot,1,2))").ToListAsync();
}
return new JsonResult(LstPreferredTimeSlot);
}
The stored procedure is returning null value, I executed the query separately in SQL Server Management Studio, it's returning the value.
Any help would be appreciated!
Edited create.cshtml.cs
if (Duration == "1 Hour")
{
var LstPreferredTimeSlot = _context.HourlyBasedView.FromSqlRaw("EXEC dbo.AvailableHourSlots #BookedDate = {0}, #ActivityName = {1}", BookingDate, ActivityName).
AsNoTracking().ToList();
}

Date parameter was passed wrongly. Corrected version is as shown below
if (Duration == "1 Hour")
{
var LstPreferredTimeSlot = _context.HourlyBasedView.FromSqlRaw("EXEC dbo.AvailableHourSlots #BookedDate = {0}, #ActivityName = {1}", BookingDate, ActivityName).AsNoTracking().ToList();
}

Related

How to save the record mutipule table using Asp.net MVC Json

i am creating simple sales system for my final year project. i am creating a sales Form. attached the screen shot image below how the form look like.
after sales completed i need to save the data into multiple table along with the lastinsert id. if i click print invoice button. i have a tables in the database sales,sales product i shown the shot shotimage below.i don't how to save records into multipule table with lastinsert id.
enter image description here
Sales Table
id date subtotal
Sales_Product Table
id sales_id product_id price qty total
Code which i tried
jQuery
function addProject() {
var table_data = [];
$('#product_list tbody tr').each(function (row, tr) {
var sub = {
//these records i am going to add into sales table
'barcode': $(tr).find('td:eq(1)').text(),
'pname': $(tr).find('td:eq(2)').text(),
'pro_price': $(tr).find('td:eq(3)').text(),
'qty': $(tr).find('td:eq(4)').text(),
'total_cost': $(tr).find('td:eq(5)').text(),
};
table_data.push(sub);
});
//these records i am going to add into sales
var total = $("#total").val();
$.ajax({
type: 'POST',
url: '/product/Save',
dataType: 'JSON',
data: {
total: $('#total').val(), data: table_data
},
success: function (data) {
console.log(_data);
var msg;
if (isNew) {
msg = "Sales Completed";
}
last_id = data.last_id
window.location.href = "print.php?last_id=" + last_id;
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
}
});
}
Controller
[HttpPost]
public ActionResult Save(sale s)
{
bool status = false;
if (ModelState.IsValid)
{
using (saleEntities3 dc = new saleEntities3())
{
//Sales table
var v = dc.sales.Where(a => a.id == s.id).FirstOrDefault();
dc.sales.Add(v);
dc.SaveChanges();
v.id = s.id; // lastinsertid
//how to add into lastinsertid as a sales product table as a sales_id colum
//Sales product table i don't how to add
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}
saleEntities3
public partial class saleEntities3 : DbContext
{
public saleEntities3()
: base("name=saleEntities3")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<product> products { get; set; }
public virtual DbSet<sale> sales { get; set; }
public virtual DbSet<sales_product> sales_product { get; set; }
}
}
To save in the Sales_Product table you need to save with the id of the saved sales according to your table structure
[HttpPost]
public ActionResult Save(sale s)
{
bool status = false;
if (ModelState.IsValid)
{
using (saleEntities3 dc = new saleEntities3())
{
//Sales table
var v = dc.sales.Where(a => a.id == s.id).FirstOrDefault();
dc.sales.Add(v);
dc.SaveChanges();
dc.sales_product.Add(new sales_product{
sales_id = s.id,
product_id = s.barcode, //I believe this is the product id
price = s.pro_price,
quantity = s.qty,
total = s.total_cost
});
dc.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status = status } };
}

How to reload session values

I am sending data from view to controller using ajax , modelID , catId etc and searching data from database against these parameters, but first time load session values but after that if i change its value cant not load session values.
$("#ModelID").change(function () {
var Cat = $("#Cat").val();
var subcat = $("#CatID").val();
if (Cat != "" & subcat != "") {
$("#modalvalag").modal("show");
$.ajax({
type: 'post',
url: '/Inventory/CatSubCatAgainstModal',
data: {
Cat: $("#Cat").val(),
SubCat: $("#CatID").val(),
ModelID: $("#ModelID").val()
},
success: function (response) {
$('#noo').html(response);
}
});
}
else {
alert("Please select Category Or sub category to complete this process");
}
return false
});
Here is controller code:
public ActionResult CatSubCatAgainstModal(int Cat = 0, int SubCat = 0 , int ModelID = 0)
{
// var dta = db.ItemsCatSubCats.Where(m => m.CatID == CatID & m.SubCatID == SubCatID).FirstOrDefault();
//Session["ItemName"] = dta.Category.Catgory + "|" + dta.SubCategory.SubCat;
Session["CatID"] = Cat;
Session["SubCat"] = SubCat;
Session["ModelID"] = ModelID;
var data = db.ItemAttributes.Where(m => m.CatID == Cat & m.SubCatID == SubCat & m.ModelID == ModelID).ToList();
int c = 0;
foreach(var itm in data){
Session["value"+c] = itm.AttributeValue;
c++;
}
return RedirectToAction("AttributListForValue");
}

How to send message/notification to browser/client in Kendo Mvc Ajax Bound Grid (confirm update or create) ( by cookies)

how to send notification to client in kendo mvc ajax bound ,
i do not know if this is good way ..
of course you can add ModelState.AddModelError("notification","….msg.")
and …. But it tell to datasource ajax action failed.. So..
Addclass:
public class AjaxErrorMsg
{
public AjaxErrorMsg()
{
CssClass = "gray";
AutoHide = false;
AutoHideDelay = 200;
Kind = "error";
Title = "error";
}
public string Msg { get; set; }
public string Kind { get; set; }
public Boolean AutoHide { get; set; }
public Int32 AutoHideDelay { get; set; }
public string CssClass { get; set; }
public string Title { get; set; }
}
In controller
public void StoreMessageInCookie(string msg, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
StoreMessageInCookie(new Exception(msg), isError, msgDivClass, preMessage, msgTitle);
}
public void StoreMessageInCookie(Exception ee, Boolean isError = false, string msgDivClass = "", string preMessage = "", string msgTitle = "")
{
List<AjaxErrorMsg> rs;
var js = new JavaScriptSerializer();
if (this.Response.Cookies[Common1.MsgCookie].HasKeys )
{
try
{
rs = js.Deserialize<List<AjaxErrorMsg>>(this.Response.Cookies[Common1.MsgCookie].Value);
}
catch
{
rs = new List<AjaxErrorMsg>();
}
}
else
{
rs = new List<AjaxErrorMsg>();
}
var msg0 = new AjaxErrorMsg();
if (isError)
{
msgDivClass = msgDivClass == "" ? "DivAlarmStyle6 fontMitra" : msgDivClass;
msg0.Kind = "error";
msg0.AutoHide = false;
msg0.Title = "Error";
}
else
{
msg0.Kind = "alert";
msg0.AutoHide = true;
msg0.Title = "Warning";
}
msg0.Title = msgTitle == "" ? msg0.Title : msgTitle;
msg0.Msg = preMessage + cm2.FilterMessageText(ee, IsAdminUser);
if (msgDivClass.Trim() != "")
msg0.Msg = Common1.WrapTextInDivWithClass(msg0.Msg, msgDivClass);
rs.Add(msg0);
this.Response.Cookies.Add(new HttpCookie(Common1.MsgCookie, js.Serialize(rs)));
}
cm2.FilterMessageText is function to remove database object name from error message string ..also include any inner exception message
Then when you what to send message use command
StoreMessageInCookie("Message 1 2 ! ");
And in your MainProject.js
Add all of code below
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
function ReadAnShowCookieForDeliverMessages() {
try {
var listMsg = readCookie("CookieForDeliverMessages")
if (!!listMsg) {
eraseCookie("CookieForDeliverMessages");
ShowAndLogMessageListOfAjaxError($.parseJSON(listMsg));
}
} catch (ee) {
alert(" error in ReadAnShowCookieForDeliverMessages")
}
}
function ShowAndLogMessageListOfAjaxError(ListOfAjaxError) {
if (ListOfAjaxError == undefined)
return;
ListOfAjaxError.forEach(function (AjaxError) {
ShowAndLogMessageByAjaxErrorClass(AjaxError)
})
}
function ShowAndLogMessageByAjaxErrorClass(AjaxError) {
if ((AjaxError != undefined) && (AjaxError.Msg != "")) {
// I used freeow => https://github.com/pjdietz/Freeow
$("#freeow").freeow(AjaxError.Title, AjaxError.Msg, { classes: [AjaxError.CssClass, AjaxError.Kind], autoHide: AjaxError.AutoHide, autoHideDelay: AjaxError.AutoHideDelay });
// LogMsg(AjaxError.Msg, AjaxError.Title); function to log message on client
}
}
$(function () {
MyAjaxSetting();
ReadAnShowCookieForDeliverMessages();
}
function MyAjaxSetting() {
$(document).ajaxComplete(function (o) {
ReadAnShowCookieForDeliverMessages()
});
}

how i could iterate over json array of array

i want to iterate over a json array of arrays from th controller i want to know how i could iterate over it
i need help: nay could help me i'm new to json and mvc
//server code
var jsonData = new
{
rows =
(from bathymetrie in bathymetries
select new
{
count = bathymetries.Count,
Id = bathymetrie.Id,
date = (bathymetrie.displayedDate != null) ?
bathymetrie.displayedDate.ToString() : ""
}).ToArray()
};
//client code
success: function (data) {
bathyms = "{";
for (var i = 0; i < data[1].count; i++) {
bathyms += el[i].Id + " : " + el[i].date;
alert(el[i].Id);
alert(el[i].date);
console.log(el[i].date);
if (i != data[0].count) {
bathyms += ",";
}
}
bathyms += "}";
}
Your data is an object with single field row, which contains an array of objects. Thus, iteration should look like this:
for (var i = 0; i < data.rows.length; i++) {
var element = data.rows[i];
// use element.Id, element.count and element.date
Say if you have your model like this -
public class Data
{
public int Id { get; set; }
public int Count { get; set; }
public string Date { get; set; }
}
And you are returning JsonResult of Array object like this -
public ActionResult GetJson()
{
Data[] a = new Data[2];
a[0] = new Data() { Count = 10, Id = 1, Date = "2/19/2014" };
a[1] = new Data() { Count = 20, Id = 2, Date = "3/19/2014" };
return new JsonResult() { Data = a };
}
Then you can invoke this action in JQuery in the following way -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, value) {
alert(value.Id + ' ' + value.Count + ' ' + value.Date);
});
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()" />
Please observe following code which will iterate array -
success: function (data) {
$.each(data, function (key, value) {
alert(value.Id + ' ' + value.Count + ' ' + value.Date);
});
Output would be N number of alerts based on N elements in array like below -

Nullable<System.DateTime> and BreezeJS

I have this class:
public partial class VehicleSize
{
public VehicleSize()
{
}
public System.Guid VehicleSizeId { get; set; }
public int Title { get; set; }
public int SizeOrder { get; set; }
public System.DateTime DateCreated { get; set; }
public Nullable<System.DateTime> DateDeleted { get; set; }
}
I'm using with BreezeJS.
Handling of Nullable seems a bit odd. This field is meant to be optional. But it complains until I explicitly set DateDeleted = null from the javascript. If I don't set the field to null I'll get "Problem saving TypeError: entity.dateDeleted is null".
It seems if i inspect the .dateDeleted property in javascript it is a javascript Date object but getTime isNAN. Shouldn't it be null in this case instead and the BreezeJS validator skip validating it as the field is null.
The Meta data from the server defines the field as this:
"name": "DateDeleted",
"type": "Edm.DateTime",
"nullable": "true"
Does anyone have an idea on how I create an optional DateTime field?
Further to my original post. The problem seems to be related to exporting Entities from one entity manager to another. A Date field that starts out as "null" becomes "Invalid Date" after its imported again as demonstrated by this code:
var vehicleSizeId = 'E9DA5803-BB65-4751-AA22-17B54A1EE7C1';
alert('getting vehicle from db');
var query = breeze.EntityQuery
.from("VehicleSizes")
.where("vehicleSizeId", "==", vehicleSizeId);
var em = new breeze.EntityManager("api/Todo");
em.enableSaveQueuing(true);
var sandBoxEm = em.createEmptyCopy();
sandBoxEm.enableSaveQueuing(true);
em.executeQuery(query)
.then(function (data) {
alert('Found the vehicle size in the original entity manager')
var entity = data.results[0];
alert('Org Date Deleted == ' + entity.dateDeleted); // Its null at this point
var bundle = em.exportEntities();
sandBoxEm.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
});
sandBoxEm.executeQuery(query)
.then(function (data) {
alert('Found the vehicle size')
var entity = data.results[0];
alert('Date Deleted == ' + entity.dateDeleted); // Now its invalid date
entity.sizeOrder = entity.sizeOrder + 1;
entity.titleTranslation.text = entity.titleTranslation.text + "_x";
//entity.titleTranslation.dateDeleted = null;
//entity.dateDeleted = null;
try {
sandBoxEm.saveChanges().then(
function () {
alert('It saved ok');
}).fail(
function (error) {
var firstItem = error.entitiesWithErrors[0];
var firstError = firstItem.entityAspect.getValidationErrors()[0];
var msg = "prop: " + firstError.property.parentType.name + " = " + firstError.errorMessage;
alert(msg);
}
);
}
catch (ex) {
alert( "Problem saving " + ex );
}
}
).fail(
function () {
alert('Getting the vehicle size failed');
});
Edit: May 8, 2013 - The issue with importing a previously exported null date is now fixed in v 1.3.3 and available on the Breeze website.
Not sure what you are experiencing. I just wrote a unit test to try and confirm what you are seeing and are not able to repro your issue. I am running this against an Employee model where the "birthDate" also defined as a Nullable.
All tests pass on this:
var em = newEm(); // creates a new EntityManager
var emp = em.createEntity("Employee", { firstName: "Joe", lastName: "Smith" });
ok(emp.entityAspect.entityState === breeze.EntityState.Added, "entityState should be 'Added'");
var birthDate = emp.getProperty("birthDate");
ok(birthDate === null, "birthDate should be null");
var q = EntityQuery.from("Employees").where("birthDate", "==", null);
stop();
em.executeQuery(q).then(function(data) {
var empsWithNullBirthDates = data.results;
ok(empsWithNullBirthDates.length > 0, "should be at least 1 employee with a null birthdate");
empsWithNullBirthDates.forEach(function(emp) {
var birthDate = emp.getProperty("birthDate");
ok(birthDate === null, "queried birthDate should be null");
});
}).fail(testFns.handleFail).fin(start);

Resources