How to load value of last employeeid + 1 in add action - asp.net-mvc

I have controller name emp have action add
i need when action add view loaded display last value increased by one in
employeeid textbox .
meaning suppose i have in employee table employeeid value 1 then when action add
view loaded employeeid must have 2 .
so that how to do that please ?
in action what i write
[httpget]
Hide Copy Code
public IActionResult Create()
{
what i write here
}
on view add
what i write here
<div class="form-group">
<label asp-for="EmployeeId" class="control-label"></label>
<input asp-for="EmployeeId" class="form-control" />
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
What I have tried:
var results = _context.GetAll().Where(Employee => Employee.EmployeeId> Employee.EmployeeId).OrderBy(Employee => Employee.EmployeeId).FirstOrDefault();
and i pass model to view
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmployeeId" class="control-label"></label>
<input asp-for="EmployeeId" class="form-control" />
<span asp-validation-for="EmployeeId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BranchCode" class="control-label"></label>
<input asp-for="BranchCode" class="form-control" />
<span asp-validation-for="BranchCode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeName" class="control-label"></label>
<input asp-for="EmployeeName" class="form-control" />
<span asp-validation-for="EmployeeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="EmployeeAge" class="control-label"></label>
<input asp-for="EmployeeAge" class="form-control" />
<span asp-validation-for="EmployeeAge" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="JoinDate" class="control-label"></label>
<input asp-for="JoinDate" class="form-control" />
<span asp-validation-for="JoinDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BirthDate" class="control-label"></label>
<input asp-for="BirthDate" class="form-control" />
<span asp-validation-for="BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input asp-for="Active" /> #Html.DisplayNameFor(model => model.Active)
</label>
</div>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>

Please don't use .GetAll() , it'll be cause for performance issue. it means you are loading all employee records to the application side, then you are actually querying to loaded employee data. just think about if you have 50K+ employee. So, you have to use LINQ IQueryable extension methods, which will generate the SQL operation based on your design query.
Help Link:.NET Entity Framework - IEnumerable VS. IQueryable
Please Try This, if you want to do some other expressions.
context.Employee.Select(x => x.EmployeeId).DefaultIfEmpty(0).Max()+1

If your model have property EmployeeId then set this value to it like below.
public IActionResult Create()
{
var model = new Employee();
model.EmployeeId = _context.GetAll().Max(Employee => Employee.EmployeeId).FirstOrDefault() + 1;
return View(model);
}
Or if you don't have Model to pass to View then use ViewBag.
ViewBag["maxEmployeeId"] = _context.GetAll().Max(Employee => Employee.EmployeeId).FirstOrDefault() + 1;

Related

ASP.NET MVC - IHtmlFormElement's GetSubmission returns null

I'm making a POST request through an MVC controller using ASP.NET MVC and while unit testing I'm getting 'Object reference not set to an instance of an Object' from an IHtmlFormElement's GetSubmission() method. The test finds the button and the button itself is not null, but when the test calls the GetSubmission() with the submit button as a parameter it returns null.
Everything works fine from browser.
This is my Add.cshtml file content:
#model MVCPhones.Data.Phone
<form method="post" asp-action="Add">
<div class="form-group">
<label asp-for="Make" class="control-label">Make</label>
<input asp-for="Make" type="text" class="form-control" />
</div>
<div class="form-group">
<label asp-for="Model" class="control-label">Model</label>
<input asp-for="Model" type="text" class="form-control" />
</div>
<div class="form-group">
<label asp-for="RAM" class="control-label">RAM</label>
<input asp-for="RAM" type="number" class="form-control" />
</div>
<div class="form-group">
<label asp-for="PublishDate" class="control-label">PublishDate</label>
<input asp-for="PublishDate" type="date" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
Here is my PhonesController post method:
public async Task<IActionResult> Add(Phone phone)
{
try
{
phone.Created = DateTime.Now;
phone.Modified = DateTime.Now;
await _context.Phones.AddAsync(phone);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch
{
return View();
}
}
Here is the section that gives the error:
Error

How to compare emails in javascript?

I am trying to make an edit profile page in which user can update its current email or pwd by inputting current email and password and then give new ones. I am also sending whole data of user(including username and password) when he sign in through viewdata.
#{
var user = (User)ViewData["User"];
}
<div class="account-info mt-3">
<fieldset class="border border-dark p-3">
<legend class="float-none w-auto">Account Info</legend>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter Your Current Email</label>
<input type="email" class="form-control" name="Username" id="prevemail"/>
</div>
<div class="mb-3 simpleinfo">
<label for="prevpwd" class="form-label">Enter Your Current Password</label>
<input type="password" class="form-control" name="Pwd" id="prevpwd"/>
<button type="button" class="btn btn-success mt-4 checkcred">Update Credentials</button>
</div>
<div class="mb-3 simpleinfo">
<label for="email" class="form-label">Enter new Email</label>
<input asp-for="Username" disabled type="email" class="form-control" id="newemail">
</div>
<div class="mb-3 simpleinfo">
<label for="newpwd" class="form-label">Enter New Password</label>
<input type="password" disabled class="form-control" asp-for="Password" id="newpwd">
</div>
</fieldset>
</div>
Now i want to compare the email that user enters and the email that is present in the user object.
here's my code for this:
<script>
$('.checkcred').click(function() {
var prevemail = $('#prevemail').val();
var prevpassword=$('#prevpwd').val();
if(prevemail==#user.Username&&prevpassword==#user.Password)
{
alert("Validated");
}
else
{
alert("not validated");
}
});
</script>
But it is giving me syntax error on Console: Invalid or unexpected token.
Please lemme know what i am doing wrong.

Passing Current Model to partial View, Handling Large from Server To Clients

i want to pass All Input values of View to My Partial View(Passing User Order to Show Order Summary) but all values got null in partial View Below is My Code.
Submit
<div id="myModal_#Model.CustRef" class="modal fade" role="dialog">
<div class="modal-dialog" style="position:absolute; left:10%;">
<!-- Modal content-->
<div class="modal-content" style="width:80vw;">
<div class="modal-header ">
<h4 class="modal-title"><i class="fas fa-shopping-cart"></i> Order Summary</h4>
<button type="button" class="close" data-dismiss="modal">Back</button>
</div>
<div class="modal-body">
...Disabled Inputs...
</div>
</div>
</div>
</div>
My Create Order View
<form asp-action="Create">
....
#*<partial name="~/Views/Order/OrderSummary.cshtml" model="Model" />*#
#await Html.PartialAsync("~/Views/Order/OrderSummary.cshtml", new OrderViewModel() { cus_name = Model.cus_name, cus_phone = Model.cus_phone, CustRef = Model.CustRef, Phoneid = Model.Phoneid, modelId = Model.modelId, Quantity = Model.Quantity, Address = Model.Address, CityId = Model.CityId, Date = Model.Date, store_id = Model.store_id })
</form>
Second Question
My Second Question is i have large data to pass to View(Admin Dashboard) to Complete Statistics but its taking too much time. Please tell me any other Efficient way to increase performance.
You need to pass the current input model to the controller through ajax and return
to render the new partial view.
Please refer to the following code:
Controller:
public class OrderController : Controller
{
public IActionResult Index()
{
OrderViewModel orderView = new OrderViewModel();
return View(orderView);
}
public PartialViewResult ShowParitalView(OrderViewModel orderView)
{
return PartialView("OrderSummary", orderView);
}
}
Index view:
#using WebApplication_core_mvc.Models;
#model OrderViewModel
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts{
<script>
$(function () {
$("a").click(function () {
event.preventDefault();
$("div .modal").attr("id", "myModal_" + $("#cus_name").val());
$("a").attr("data-target", "#myModal_" + $("#cus_name").val());
$.ajax({
type: "POST",
url: "/Order/ShowParitalView",
data: $("form").serialize(),
success: function (data) {
$('#partial').html(data);
$("#myModal_" + $("#cus_name").val()).modal('show');
}
})
})
});
</script>
}
<form asp-action="Create">
<div class="form-group">
<label asp-for="cus_name" class="control-label"></label>
<input asp-for="cus_name" class="form-control" />
<span asp-validation-for="cus_name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="cus_phone" class="control-label"></label>
<input asp-for="cus_phone" class="form-control" />
<span asp-validation-for="cus_phone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CustRef" class="control-label"></label>
<input asp-for="CustRef" class="form-control" />
<span asp-validation-for="CustRef" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Phoneid" class="control-label"></label>
<input asp-for="Phoneid" class="form-control" />
<span asp-validation-for="Phoneid" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="modelId" class="control-label"></label>
<input asp-for="modelId" class="form-control" />
<span asp-validation-for="modelId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Quantity" class="control-label"></label>
<input asp-for="Quantity" class="form-control" />
<span asp-validation-for="Quantity" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label>
<input asp-for="Address" class="form-control" />
<span asp-validation-for="Address" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CityId" class="control-label"></label>
<input asp-for="CityId" class="form-control" />
<span asp-validation-for="CityId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Date" class="control-label"></label>
<input asp-for="Date" class="form-control" />
<span asp-validation-for="Date" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="store_id" class="control-label"></label>
<input asp-for="store_id" class="form-control" />
<span asp-validation-for="store_id" class="text-danger"></span>
</div>
<a href="#" data-toggle="modal" data-target="#myModal_#Model.CustRef"
style="border-radius: 1.5rem; margin-right:8%; margin-top: 1%; border: none;
padding:10px 2%; background: #0062cc; color: #fff; font-weight: 600; width:20%;
cursor: pointer; text-align:center; font-weight:bolder;">
Submit
</a>
<div id="myModal_#Model.CustRef" class="modal" role="dialog">
<div class="modal-dialog" style="position:absolute; left:10%;">
<!-- Modal content-->
<div class="modal-content" style="width:80vw;">
<div class="modal-header ">
<h4 class="modal-title"><i class="fas fa-shopping-cart"></i> Order Summary</h4>
<button type="button" class="close" data-dismiss="modal">Back</button>
</div>
<div class="modal-body">
<div id="partial">
</div>
</div>
</div>
</div>
</div>
</form>
OrderSummary Partial View:
#using WebApplication_core_mvc.Models;
#model OrderViewModel
<div class="form-group">
<label asp-for="cus_name" class="control-label"></label>
<input asp-for="cus_name" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="cus_phone" class="control-label"></label>
<input asp-for="cus_phone" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="CustRef" class="control-label"></label>
<input asp-for="CustRef" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="Phoneid" class="control-label"></label>
<input asp-for="Phoneid" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="modelId" class="control-label"></label>
<input asp-for="modelId" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="Quantity" class="control-label"></label>
<input asp-for="Quantity" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="Address" class="control-label"></label>
<input asp-for="Address" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="CityId" class="control-label"></label>
<input asp-for="CityId" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="Date" class="control-label"></label>
<input asp-for="Date" class="form-control" disabled/>
</div>
<div class="form-group">
<label asp-for="store_id" class="control-label"></label>
<input asp-for="store_id" class="form-control" disabled/>
</div>
Here is the result:
For the second question, there are too many SQL query statements in your code, you can try to improve performance by referring to this.

Input validation generating data-* attributes ONLY on Primary key and checkbox type input tags

I've created a sample ASP.NET MVC Core 1.1 web app created using VS2015-Update3. It generates input tags with data -* attributes only on a model property that is a Primary Key, and on a property that is of type bool. For instance, in the following example the generated html (shown below) is showing the data-attributes only on the input tag generated for properties MyEntityId and Prop2 of the model. NOTE: I'm using the default ASP.NET Core Web Application template that automatically installs Jquery, Bootstrap, etc.
Model:
public class MyEntity
{
public int MyEntityId { get; set; }
public string Prop1 { get; set; }
[Column(TypeName = "char(2)")]
[RegularExpression(#"^[0-9]{2,2}$", ErrorMessage = "Must enter two digit numbers"), StringLength(2)]
public string TestCode { get; set; }
public DateTime? StartDate { get; set; }
public bool Prop2 { get; set; }
}
View
<form asp-controller="TestController" asp-action="TestAction" method="post" class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<div><input type="hidden" asp-for="MyEntityId" /></div>
<div class="form-group">
<label asp-for="Prop1" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Prop1" class="form-control" style="margin-top:15px;" />
<span asp-validation-for="Prop1" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="TestCode" class="col-md-2 control-label"></label>
<div class="col-md-2">
<input asp-for="TestCode" class="form-control" />
<span asp-validation-for="TestCode" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="StartDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="StartDate" type="date" class="form-control" />
<span asp-validation-for="StartDate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Prop2" class="col-md-2 control-label"></label>
<div class="col-md-1">
<input asp-for="Prop2" class="form-control" style="zoom:0.5;margin-top:25px;" />
<span asp-validation-for="Prop2" class="text-danger"></span>
</div>
</div>
<button type="submit" name="submit" value="testVal">Save</button>
</form>
Generated Html:
<div><input type="hidden" data-val="true" data-val-required="The MyEntityId field is required." id="MyEntityId" name="MyEntityId" value="54321"></div>
<div class="form-group">
<label class="col-md-2 control-label" for="StateName">Prop1</label>
<div class="col-md-2">
<input class="form-control" readonly="" type="text" id="Prop1" name="Prop1" value="TestVal">
<span class="text-danger field-validation-valid" data-valmsg-for="Prop1" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="TestCode">TestCode</label>
<div class="col-md-2">
<input class="form-control" type="text" id="TestCode" name="TestCode" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="TestCode" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="StartDate">Start Date</label>
<div class="col-md-10">
<input type="date" class="form-control" id="StartDate" name="StartDate" value="2015-10-01">
<span class="text-danger field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="Prop2">Test Prop2</label>
<div class="col-md-1">
<input class="form-control" data-val="true" data-val-required="Test Prop2 is required." id="Prop2" name="Prop2" style="zoom:0.5;margin-top:25px;" type="checkbox" value="true">
<span class="text-danger field-validation-valid" data-valmsg-for="Prop2" data-valmsg-replace="true"></span>
</div>
</div>
I'm assuming your issue is that TestCode does not have validation on it, despite having both RegularExpression and StringLength attributes applied. MyEntityId and Prop2 are non-nullable, so there's an implicit required validation for those, while Prop1 and StartDate are nullable and do not have any explicit validation applied. As a result, those are rightly not validated.
TestCode is weird, though. I'm not sure you'd actually get data-* attributes, as both the regular expression and string length can be satisfied using the HTML attributes pattern and maxlength, respectively. But, you should then have pattern and maxlength applied to the input for TestCode which is not the case.
According to the docs, the code you have should work, and at the least, it seems that StringLength is applied via data-val-maxlength rather than (or perhaps in addition to) using the maxlength attribute. There's either some bug at play, or there's something else in your codebase that is preventing the correct behavior from occurring. However, without more code, it's impossible to say.

Google's new recaptcha not validating

Am I missing something? I copied this code snippet over:
Automatically render the reCAPTCHA widget
I entered my registered data-sitekey. The reCAPTCHA displays and works when I check the box, but if I don't check the box and submit my form, the reCAPTCHA doesn't stop the user submission and my controller processes the request.
#model Medicaid.WebUI.ViewModels.RequestModel
<script src='https://www.google.com/recaptcha/api.js' async defer></script>
<table class="table">
<tr>
<td>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "request-form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
<fieldset>
<legend>Request</legend>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">First Name</label>
<div class="col-lg-10">
<input type="text" value="#Model.FirstName" class="form-control" maxlength="50" name="FirstName" id="FirstName" placeholder="First Name" required>
</div>
</div>
<div class="form-group">
<label for="inputLastName" class="col-lg-2 control-label">Last Name</label>
<div class="col-lg-10">
<input type="text" value="#Model.LastName" class="form-control" maxlength="50" name="LastName" id="LastName" placeholder="Last Name" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="email" value="#Model.Email" class="form-control" maxlength="100" name="Email" id="Email" placeholder="Email" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2"><br /><br />
<div class="g-recaptcha" data-sitekey="IenterMykeyHere"></div><br /><br />
<button type="submit" class="btn btn-primary">Submit Request</button>
</div>
</div>
</fieldset>
}
</td>
</tr>
</table>
<br /><br />
#Html.ValidationSummary()
I was having this issue and re-read the documentation, and worked it out as the following:
function onBegin() {
$("input[type='hidden']").val(grecaptcha.getResponse());
}
You have to add a javascript function to the "onBegin" parameter of the AjaxOptions object from the MVC html helper - that will copy the value of the widget's response to a hidden variable you need to declare inside your form, so the submit button sends it to the controller. Don't forget to add a variable with the same name to the "RequestModel" view model so that the mvc model-binding passes it and you then will be able, in the server, to know if the user has clicked the button or not.
#using (Ajax.BeginForm("NewRecaptchaVerify", "ReCaptcha", new AjaxOptions
{
HttpMethod = "Post",
OnSuccess = "onSuccess",
OnFailure = "onFailure",
OnBegin = "onBegin",
OnComplete = "onComplete"
}))
{
#Html.HiddenFor(m => m.Response)
<div class="g-recaptcha" data-sitekey="your-site-key"></div>
<input type="submit" id="btnSubmit" value="Submit" />
}
(for the record, I am now facing the problem of knowing, in the server, in cases where the widget prompted the user to enter a text input, after clicking the button - whether he/she entered the text or not. Seems to me that in the end I will have no way out other than performing a GET request, in the server, to the widget's api, as they put it in the documentation: https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address

Resources