Good Day! I am a newbie on ASP.NET (MVC) and trying to display a value (from a Stored Procedure) after the value of the date has been changed. This is what it looks like on the design Once the date is picked, the user will click the Create button and the value should be displayed on the "Sales" textbox
This is my Stored Procedure for it
CREATE PROCEDURE [dbo].[SP_DAILY_SALES]
-- Add the parameters for the stored procedure here
#Order_date date
AS
BEGIN TRANSACTION;
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
BEGIN TRY
SET NOCOUNT OFF;
DECLARE #SumTable table
(
dailySales decimal (18,2)
)
DECLARE #dailySales decimal(18,2)
SET #dailySales = (
SELECT SUM(NET_AMOUNT)
FROM [ORDER]
WHERE ORDER_DATE=#Order_date)
INSERT INTO #SumTable (dailySales)
VALUES (#dailySales)
-- Insert statements for procedure here
SELECT dailySales
FROM #SumTable
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH;
and this is where I call it (Repository)
public bool DisplayDailySales(DateTime orderdate)
{
connection();
SqlCommand com = new SqlCommand("SP_DAILY_SALES", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add("#Order_date", SqlDbType.DateTime).Value = orderdate;
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
My Controller
[HttpGet]
public ActionResult Statistics()
{
OrderVM dSales = new OrderVM();
var currentdate = DateTime.Now;
dSales.ORDER_DATE = currentdate;
return View();
}
[HttpPost]
public ActionResult Statistics(OrderVM order)
{
try
{
DateTime orderdate = order.ORDER_DATE;
ViewData["ORDERDATE"] = orderdate;
if (ModelState.IsValid)
{
OrderRepository orderRepo = new OrderRepository();
orderRepo.DisplayDailySales(orderdate);
}
return View();
}
catch
{
return View();
}
}
And lastly, in my view as of now is this
<div class="panel-body">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.ORDER_DATE, "Date", htmlAttributes: new { #class = "col-xs-4 col-sm-offset-1 col-sm-4" })
<div class="col-lg-6 col-lg-6 col-md-6 col-md-6 col-sm-6 col-sm-6 col-xs-6 col-xs-6">
#Html.TextBoxFor(model => model.ORDER_DATE, "{0:yyyy-MM-dd}", new { #class = "form-control", #type = "date", #id = "Orderdate" })
#Html.ValidationMessageFor(model => model.ORDER_DATE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dailySales, "Sales", htmlAttributes: new { #class = "col-xs-4 col-sm-offset-1 col-sm-4" })
<div class="col-lg-6 col-lg-6 col-md-6 col-md-6 col-sm-6 col-sm-6 col-xs-6 col-xs-6">
#Html.TextBoxFor(model => model.dailySales, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.dailySales, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-lg-3 pull-right">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
</div>
Hope someone can help me out on this. Thank You!
Related
I am using react-date-range plugin to select a date range in a application. It is shown as follows.
export function Dashboard() {
historyDate = [];
historyAmount = [];
const [dashboardSummary] = useDashboardSummary();
const [a, fetchDashboardSummary] = useDashboardSummary();
let [req, setReq] = useState<DashboardSummaryReqGqlInput>({
startDate: start.format('YYYY-MM-DD'),
endDate: end.format('YYYY-MM-DD')
});
useEffect(() => {
fetchDashboardSummary({
req
});
}, [req])
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
if (isSuccess(dashboardSummary)) {
dailyTotalCount = dashboardSummary.result.dashboardSummary.dailyTxnCount;
dailyValue = dashboardSummary.result.dashboardSummary.dailyTxnValue;
dailySuccessCount = dashboardSummary.result.dashboardSummary.dailySuccessTxnCount;
let historyData = dashboardSummary.result.dashboardSummary.amountHistory
for(let x in historyData) {
historyAmount.push(historyData[x].amount!)
historyDate.push(historyData[x].date!)
}
}
function setDateRange(startDate: Date, endDate: Date){
console.log("setDateRange: start:" , startDate + " end:", endDate)
console.log(moment(startDate).format("YYYY-MM-DD"))
start = moment(startDate)
end = moment(endDate)
setReq({startDate: moment(startDate).format("YYYY-MM-DD"), endDate: moment(endDate).format("YYYY-MM-DD")})
}
const selectionRange = {
startDate: new Date(),
endDate: new Date(),
key: 'selection',
}
function handleSelect(ranges: any) {
setDateRange(ranges.selection.startDate, ranges.selection.endDate)
showDateRangePicker = false
}
function onClickDateRangePicker() {
console.log("--------onClickRangePicker")
showDateRangePicker = true
setReq({startDate: moment(start).format("YYYY-MM-DD"), endDate: moment(end).format("YYYY-MM-DD")})
}
return <div className="container-fluid">
<div className="row">
<div className="col-lg-2 col-md-3 offset-lg-2 offset-md-3 second-sidebar">
<p>Last Transactions</p>
<RecentTransactions/>
</div>
<main role="main" className="col-lg-8 col-md-6 ml-sm-auto p-0">
<div className="sub-header-dashboard">
<div className="row">
<div className="col-lg-6">
<h5 className="sub-text mt-lg-2 ml-md-0 ml-5">Dashboard</h5>
</div>
<div className="col-lg-6">
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text" onClick={onClickDateRangePicker}><i className="fas fa-calendar-alt"></i></span>
</div>
<div id={"date-picker-box"} style={{display: showDateRangePicker ? "block" : "none"}}>
<DateRangePicker
className={"datepicker"}
ranges={[selectionRange]}
onChange={handleSelect}/>
</div>
<div id="reportrange" className="form-control date-range-input pt-3">
<span className="date-range-input__date"></span>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
}
export default Dashboard
I can select a date range by dragging but cannot select start and end date separately. When I click on a date it selects that date as both start date and end date. Instead I want to select start and end date separately.
Is this is available in this pluging? Or Am I doing something wrong?
I would appreciate your assistance on this challenge i'm having with retrieving the content of a database into more than one model. Three columns needed (InsBranchNo, PercentageCover and Leadcode) are available in Underwriting_InsurerPolicyDistribution table. However, Account_ClientReceiptDistribution needs the content of these 3 columns for calculation. How do I pass the content of the 1st to the second for a particular Id using the Foreach Loop.
While retrieving the data from the database for a particular ID, below is how I loaded the rows involved into the Model.Underwriting_InsurerPolicyDistribution model.
My problem is. How do i transfer these rows into Model.Account_ClientReceiptDistribution model?
Your assistance is anticipated and will be very much appreciated.
//Policy distribution
×
Insurer Risk Apportionment
Insurer Branch Code
Is Lead Insurer
Covered %
#{if (!string.IsNullOrEmpty(Model.Underwriting_PolicyFile.PolicyRefCode))
{
for (var i = 1; i <= Model.Underwriting_InsurerPolicyDistribution.Count; i++)
{
#{var n7 = string.Format("Underwriting_InsurerPolicyDistribution[X{0}].InsBranchCode", i);}
#{var n8 = string.Format("Underwriting_InsurerPolicyDistribution[X{0}].InsuerLeadCode", i);}
#{var n9 = string.Format("Underwriting_InsurerPolicyDistribution[X{0}].PercentageCover", i);}
#Html.DropDownListFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].InsBranchCode, new SelectList(Html.InsurerBranchDropDownList(), "InsBranchCode", "FullDescription", Model.Underwriting_InsurerPolicyDistribution[i - 1].InsBranchCode), new { id = n7, #class = "form-control input-sm" })
#Html.ValidationMessageFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].InsBranchCode, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].InsuerLeadCode, new { id = n8, #class = "form-control input-sm" })
#Html.ValidationMessageFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].InsuerLeadCode, "", new { #class = "text-danger" })
</td>
<td>
#Html.EditorFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].PercentageCover, new { id = n9, #class = "form-control input-sm" })
#Html.ValidationMessageFor(model => model.Underwriting_InsurerPolicyDistribution[i - 1].PercentageCover, "", new { #class = "text-danger" })
</td>
</tr>
}
}
}
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
I suggest you use select new model by linq, and define value of field based on the content values of the Underwriting_InsurerPolicyDistribution
var result = entityToEdit.Underwriting_InsurerPolicyDistribution.Select(a => new
Account_ClientReceiptDistribution {
InsBranchCode = a.InsBranchCode,
PercentageCover = a.PercentageCover,
InsuerLeadCode = a.InsuerLeadCode
}).ToList();
//pass the result into the model as shown in the line of code below
entityToEdit.Account_ClientReceiptDistribution = result;
I hope this will help someone out there.
I am trying to persist the information in the 'auction' variable, to the table 'Auction', which has not been created yet. Entity framework is supposed to create it for me I understand. As you see, my program has made it to the point where the form data is contained in the 'auction' variable. But as you can see the debugger is stopped on 'db.Auction.Add(auction)'.
Why won't the program proceed by letting the db add the data in the 'auction' variable, to the Auction table?
I'd appreciate it.
Thanks,
CM
Thank you for replying so far but the suggestions are not working. I've written in my code as well as shown the error message again which is the same message I had that started this thread.
The View
#model MvcAuction.Models.Auction
#{
ViewBag.Title = "CreateAuctionItem";
}
<h2>#ViewBag.Title.</h2>
<div id="createAuctionItemSection">
#using (Html.BeginForm("Create", "Auctions", FormMethod.Post,
new { #class = "form-horizontal", #id =
"registerForm", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create An Item For Auction.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Title, new { #class = "col-md-2 control-
label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Title, new { #class = "form-control", #id = "title" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.StartDate, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.StartDate, "{0:yyyy-MM-dd}", new { type = "date" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.EndDate, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.EndDate, "{0:yyyy-MM-dd}", new { type = "date" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.DeliveryCost, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.DeliveryCost, new { #class = "form-control", #id = "deliveryCost" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.StartBid, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.StartBid, new { #class = "form-control", #id = "startBid" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.BuyNowPrice, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.BuyNowPrice, new { #class = "form-control", #id = "buyNowPrice" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.BuyNowEnabled, new { #Value = "Show Buy Now Price?", #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.CheckBoxFor(m => m.BuyNowEnabled, new { #class = "form-control", #id = "buyNowEnabled" })
</div>
</div>
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Description, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Description, new { #class = "form-control", #id = "description" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Create Item" />
</div>
</div>
}
<img src="~/Content/Images/progress.gif" id="progress" style="display:none;" />
<h3>#ViewBag.TheMessage</h3>
</div><!--End createAuctionItemSection-->
The Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace MvcAuction.Models
{
public class Auction
{
public long Id { get; set; }
[Required]
[Column(TypeName = "varchar")]
[Display(Name = "Title")]
public String Title { get; set; }
public string ImageURL { get; set; }
[Required]
[Column(TypeName = "date")]
[Display(Name = "Start Date")]
public DateTime StartDate { get; set; }
[Required]
[Column(TypeName = "date")]
[Display(Name = "End Date")]
public DateTime EndDate { get; set; }
[Required]
[Column(TypeName = "decimal")]
[Display(Name = "Delivery Cost")]
public decimal DeliveryCost { get; set; }
[Required]
[Column(TypeName = "decimal")]
[Display(Name = "Start Bid")]
public decimal StartBid { get; set; }
[Column(TypeName = "decimal")]
[Display(Name = "Buy Now Price")]
public decimal BuyNowPrice { get; set; }
[Column(TypeName = "bool")]
[Display(Name = "Buy Now Enabled")]
public Boolean BuyNowEnabled { get; set; }
[Column(TypeName = "varchar")]
[Display(Name = "Description")]
public String Description { get; set; }
[Column(TypeName = "int")]
[Display(Name = "View Count")]
public int ViewCount = 0;
public decimal? getCurrentTopBid()
{
return StartBid;
}
}
}
The Controller Action
[HttpPost]
public ActionResult Create(Auction auction )
{
if (ModelState.IsValid)
{
var db = new AuctionsDataContext();
db.Auction.Add(auction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
Action is already apart of the DbContext class as a DbSet. Also the view already sends the Model information back you don't need that as an overloaded parameter. Change your create post to
public class AuctionsController : Controller
{
private readonly AuctionsDataContext_context;
public AuctionsController(AuctionsDataContext context)
{
_context = context;
}
public ActionResult Create ( Bind[("Id,Title,StartDate,EndDate,DeliveryCost,StartBid,BuyNowPrice,BuyNowEnabled,Description")] Auction auction)
{
if (ModelState.IsValid)
{
_context.Add(auction);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View();
}
I'm new to asp.net and MVC, and I have a problem.
I know that this is something simple but I do not know how to do it. I seek advice and would like to thank you in advance for any help.
This is my problem:
I have 2 tables: table X: ID (primary key), Number; and table Y: ID (primary key), NID (foreign key with relationship with table X), etc.
What I want to know is how to display last inserted ID into the view of table Y on an Html editor for NID the last value of ID (table X)?
For example, I create a new row in table X, and when I want to create the row in table Y that corresponds with table X to automatically get the last ID inserted in the textbox or editor?
Can anybody give me some kind of reference or an example! Thank you for your help! Sorry for any bad spelling.
Here we go . I tested this and it returned me the model properties along with files posted . This example gives you ideea how POSt method used in MVC and how to send model propertied back to controller .
//-- this is the controller
public class FileUploadDemoController : Controller
{
//
// GET: /FileUploadDemo/
public ActionResult Index()
{
// here find the last if of the FileUploadtable
var ctx = new TestDbContext();
var maxId = ctx.Fileuploads.ToList().OrderByDescending(u => u.Id).FirstOrDefault();
var newId = maxId == null ? 1 : maxId.Id + 1;
return View("Index", new FileUploadModel { Id= newId });
}
[HttpPost]
public ActionResult PostForm(FileUploadModel model)
{
// here you have NewId in model.Id method ; Now ypour table b in my case is fileeuploadhistory I want to insert a new record with this model.Id
using (var ctx = new TestDbContext())
{
var curretFile = ctx.Fileuploads.FirstOrDefault(x => x.Id == model.Id);
if (curretFile==null)
{
curretFile=new FileUploadModel { Name=model.Name , ValidFromDate= model.ValidFromDate};
}
curretFile.History = new FileUploadHistory { InsertedDate = DateTime.Now };
ctx.Fileuploads.Add(curretFile);
ctx.SaveChanges();
}
return View("Index", model);
}
}
-- These are MY EntityFramework entities and I am using same on Views as well
public class FileUploadModel
{
public FileUploadModel()
{
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string ValidFromDate { get; set; }
public int HistoryId { get; set; }
[ForeignKeyAttribute("HistoryId")]
public virtual FileUploadHistory History { get; set; }
}
public class FileUploadHistory
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime InsertedDate { get; set; }
}
-- Finaly the cshml file . The import point is to use new { enctype = "multipart/form-data" } inside BeginForm . // the page from where you will post the data . Please change you model class in place of FileUploadModel I created for me .
#model WebApplication1.Models.FileUploadModel
#using (Html.BeginForm("PostForm", "FileUploadDemo", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="panel">
<div class="panel-body">
<div class="form-group row">
<div class="col-md-2 form-label">
<label>ID:</label>
</div>
<div class="col-md-6">
#Html.TextAreaFor(x => x.Id , new { #class = "form-control" })
</div>
</div>
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Name:</label>
</div>
<div class="col-md-6">
#Html.TextAreaFor(x => x.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Date</label>
</div>
<div class="col-md-6">
#Html.TextAreaFor(x => x.ValidFromDate, new { #class = "form-control" })
</div>
</div>
<div class="col-md-10">
<div class="form-group row">
<div class="col-md-2 form-label">
<label>Select File<i class="required-field">*</i>:</label>
</div>
<div class="col-md-8">
<input type="file" class="file-upload" style="margin: 0px;" hidden="hidden" accept=".xlsx" name="file" id="file" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-3 pull-right text-right">
<button class="btn btn-primary" id="process-submission" type="submit">
Submit
</button>
</div>
</div>
</div>
</div>
}
I'm new to AngularJS, I have a form which has two numeric textboxes and I want to display sum of them:
<div ng-app>
#Html.TextBoxFor(model => model.PS_Fees, new { #ng_model = "PSFees", #class = "form-control DMPClientAccountNew", #type = "number", #step = "any" })
#Html.TextBoxFor(model => model.DMPFees, new { #ng_model = "DMPFees", #class = "form-control DMPClientAccountNew", #type = "number", #step = "any" })
<div> {{ PSFees + DMPFees }}</div>
</ div>
The output displays {{ PSFees + DMPFees }}
I don't understand why, because I don't want to add any more complicated script into this page?