How to update value progress bar bootstrap from controller in ASP .NET Core - asp.net-core-mvc

I have a table that receive email of my users for newsletter .I Show it on my dashboard with count .but now I want to show on progress bar and its percentage per last month
how do I do ? I create another view model for show count of some things
I can show count of them but I need show on progress bar too.
my viewmodel:
public class NewsLetterViewModel
{
public string Phone { get; set; }
public string Email { get; set; }
public DateTime CreateDate { get; set; }
}

You can try to use ViewBag to pass count and percentage.Here is a demo:
Action:
public IActionResult News()
{
ViewBag.Count = 0;
ViewBag.Percentage = 0;
return View();
}
[HttpPost]
public IActionResult News(NewsLetterViewModel n,int Count)
{
//you can pass the count and percentage with ViewBag here
ViewBag.Count= Count+ 1;
ViewBag.Percentage=25;
return View();
}
View:
<div>
Count:#ViewBag.Count
</div>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: #ViewBag.Percentage%;" aria-valuenow="#ViewBag.Percentage" aria-valuemin="0" aria-valuemax="100">#ViewBag.Percentage%</div>
</div>
<form method="post">
<input hidden name="Count" value="#ViewBag.Count" />
<div class="form-group">
<label asp-for="Phone" class="control-label"></label>
<input asp-for="Phone" class="form-control" />
<span asp-validation-for="Phone" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CreateDate" class="control-label"></label>
<input asp-for="CreateDate" class="form-control" />
<span asp-validation-for="CreateDate" class="text-danger"></span>
</div>
<input type="submit"value="submit" />
</form>
result:

Related

Passing data from View to Controller and back to the same View ASP Net Core MVC

Hi I got no idea how pass simple data from View to Controller which I need to generate values for update the same View, let me show code for better understanding. I want add Visit which contains Patient, Doctor and date of visit (day and hour) so in Create page I got code :
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="PatientId" class="control-label"></label>
<select asp-for="PatientId" class="form-control" asp-items="ViewBag.PatientId"></select>
</div>
<div class="form-group">
<label asp-for="DoctorId" class="control-label"></label>
<select asp-for="DoctorId" id="iddoctor" class="form-control" asp-items="ViewBag.DoctorId" onchange="go()">
</select>
</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="date" class="control-label"></label>
<select asp-for="date" class="form-control" asp-items="ViewBag.date"></select>
</div>
I select patient, doctor and date from calendar and I want send it to Controller which should generate list of avaiable hours to put in the same page in ViewBag.date so I can select also hour and finish adding visit by click "add visit"
My Controller Create function
public IActionResult Create()
{
ViewData["DoctorId"] = new SelectList(_context.Doctors, "DoctorId", "Surname" );
ViewData["PatientId"] = new SelectList(_context.Patients, "PatientId", "Surname" );
return View();
}
EDIT :
Solution in my answer below
I select patient, doctor and date from calendar and I want send it to Controller which should generate list of avaiable hours to put in the same page in ViewBag.date so I can select also hour and finish adding visit by click "add visit"
To achieve the requirement, you can try to define a new property for hour info, like below.
public class VisitViewModel
{
public int PatientId { get; set; }
public int DoctorId { get; set; }
[DataType(DataType.Date)]
public DateTime date { get; set; }
public string hour { get; set; }
}
Update View code to bind hour field
#model VisitViewModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="PatientId" class="control-label"></label>
<select asp-for="PatientId" class="form-control" asp-items="ViewBag.PatientId"></select>
</div>
<div class="form-group">
<label asp-for="DoctorId" class="control-label"></label>
<select asp-for="DoctorId" id="iddoctor" class="form-control" asp-items="ViewBag.DoctorId" onchange="go()">
</select>
</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="hour" class="control-label"></label>
<select asp-for="hour" class="form-control" asp-items="ViewBag.date"></select>
</div>
<input type="submit" value="Create" />
</form>
In action method, generate new datetime based on selected day and hour.
public IActionResult Create(VisitViewModel visit)
{
var date = visit.date.ToShortDateString();
var newdate = Convert.ToDateTime(date + " " + visit.hour);
//...
//code logic
//...
Test Result
Ok I found solution by myself. I replaced last div in my View for this one :
<div class="form-group">
<label asp-for="hour" class="control-label"></label>
<select asp-for="hour" class="form-control" asp-items="ViewBag.hour">
</select>
</div>
Next I added function "goes" to on change event to Doctor list and calendar
<select asp-for="DoctorId" id="iddoctor" class="form-control" onchange= "goes()" asp-
items="ViewBag.DoctorId">
In goes() function there is code :
$.ajax({
url: '#Url.Action("Updatedata", "Visits")',
dataType: "json",
data: { x, data: y} ,
success: function (data) {
var items = data;
var item = "";
var itemss
for (var i = 0; i < items.length; i++) {
item = items[i];
item = item.replace("0001-01-01T", "").slice(0, -3);
itemss += "<option value='" + item + "'>" + item + "
</option>"
}
$('#hour').html(itemss);},});}};
where I'm sending selected doctor id and selected date to function "updatedata" in VisitsController, which returns me list of available hours. I hope someone will find this solution useful.

How can I store records in a list request from an HttpPost

How can I store records in a list from an HttpPost request that sends an object
I want to store each record that it processes again from the view
Take the _students object and send it to a list:
List dbTempStudentList
To work locally with data and not depend on a database
[HttpPost]public ActionResult Create(Student _student)
{
return View("");
}
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public string StudentLastName { get; set; }
public string Creditbalance { get; set; }
public string CurrentBalance { get; set; }
}
My View Create
<h2>Create</h2>
<h4>Student</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="StudentID" class="control-label"></label>
<input asp-for="StudentID" class="form-control" />
<span asp-validation-for="StudentID" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StudentName" class="control-label"></label>
<input asp-for="StudentName" class="form-control" />
<span asp-validation-for="StudentName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StudentLastName" class="control-label"></label>
<input asp-for="StudentLastName" class="form-control" />
<span asp-validation-for="StudentLastName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Creditbalance" class="control-label"></label>
<input asp-for="Creditbalance" class="form-control" />
<span asp-validation-for="Creditbalance" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="CurrentBalance" class="control-label"></label>
<input asp-for="CurrentBalance" class="form-control" />
<span asp-validation-for="CurrentBalance" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
[HttpPost]
public ActionResult Create(Student _student)
{
var list = (List<Student>)Session["studentList"];
//this is for first time
if(list==null||list.Count()==0) list = new List<Student>();
list.Add(_student);
Session["studentList"]=list;
return View();
}

Asp-validation-summary="ModelOnly" does not work for compare data-validator

View Does displays Span validation but Validation summary(blank validation-summary div also not present).if i change Asp-validation-summary="All".I am not getting why it is not working with ModelOnly.
My Class
public class RegistrationViewModel
{
[Required]
[EmailAddress]
[MinLength(5)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
[Display(Name = "Confirm Password")]
public string VerifiedPassword { get; set; }
}
view
<form asp-action="Registration">
<div asp-validation-summary="ModelOnly" val class="text-danger"></div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" class="form-control" required />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="VerifiedPassword" class="control-label"></label>
<input asp-for="VerifiedPassword" class="form-control" required/>
#*<span asp-validation-for="VerifiedPassword" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-default" />
</div>
</form>
Add this to post method in the controller:
if (!ModelState.IsValid)
{
AddErrorsFromModel(ModelState.Values);
return View();
}
Also add using and AddErrorsFromModel to controller:
using Microsoft.AspNetCore.Mvc.ModelBinding;
private void AddErrorsFromModel(ModelStateDictionary.ValueEnumerable values)
{
foreach (ModelStateEntry modelState in values)
foreach (ModelError error in modelState.Errors)
{
ModelState.AddModelError(string.Empty, error.ErrorMessage.ToString());
}
}

ASP.NET Core model binding

I'm trying to bind an edit action to a model which doesn't work. Here below the controller:
[Route("[controller]/[action]")]
public class CustomerController : Controller
{
private readonly IUnitOfWork _unitOfWork;
public CustomerController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
[HttpGet("{_customerCode}")]
public IActionResult Edit(int _customerCode)
{
var customer = _unitOfWork.Customers.getCustomerByCode(_customerCode);
var customerDTO = Mapper.Map<CustomerModelDTO>(customer);
return View(customerDTO);
}
[HttpPost]
public IActionResult Edit(CustomerModelDTO model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var _customer = _unitOfWork.Customers.getCustomerByCode(model.CustomerCode);
if (_customer==null)
{
return NotFound();
}
Mapper.Map(model, _customer);
_unitOfWork.Complete();
return RedirectToAction("Detail", new { customerCode = _customer.CustomerCode });
}
}
And here is the view I am using:
#model Almiz.Dtos.CustomerModelDTO
<form asp-action="Edit" method="post">
<div class="form-horizontal">
<h4>CustomerModelDTO</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="CustomerCode" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="CustomerCode" class="form-control" />
<span asp-validation-for="CustomerCode" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="FirstName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="FirstName" class="form-control" />
<span asp-validation-for="FirstName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="MiddleName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="MiddleName" class="form-control" />
<span asp-validation-for="MiddleName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="LastName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="LastName" class="form-control" />
<span asp-validation-for="LastName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Telephone" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Telephone" class="form-control" />
<span asp-validation-for="Telephone" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Mobile" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Mobile" class="form-control" />
<span asp-validation-for="Mobile" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to Index</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
When I call the view and with the ID http://localhost:65001/Customer/Edit/1001, I get the all the information. However when I edit it and post the edited form I get resource not found error. Please help. Here below the model:
public class CustomerModelDTO
{
public int CustomerCode { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public double Telephone { get; set; }
public double Mobile { get; set; }
public string Email { get; set; }
}
I got it working. Here below the change.
[HttpPost("{customerCode}")]
public IActionResult Edit(int customerCode, CustomerModelDTO data)

Display Friendly Error Message When using Decorators in Models

New to ASP.NET Core.
I have a view:
<form asp-action="LogIn">
<div class="form-horizontal">
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="EmailAddress" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="EmailAddress" class="form-control" style="min-width:350px" />
<span asp-validation-for="EmailAddress" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Password" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Password" class="form-control" style="min-width:350px" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enter" class="btn btn-default" />
</div>
</div>
</div>
</form>
I have this Model for it:
public class Subscription
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long SubscriptionId { get; set; }
[Display(Name = "Email Address")]
[Required]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")]
public string EmailAddress { get; set; }
[NotMapped]
public string Password { get; set; }
}
So, when a User types in an email address that is not validated by the regular expression I get the error message:
How do i over-ride this 'default' error message to say (for example):
Email Address is Invalid
?
You need to add ErrorMessage property to the RegularExpression attribute like this-
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Your friendly message goes here")]

Resources