Display error message if variable isn't what i expect - c#

I'm receiving List<int> percentage as parameter in POST controller.
I'm doing that:
var prc = 0;
var prcCount = 0;
foreach (var pr in percentage)
{
prc += pr;
prcCount++;
}
if (prc != 100)
return View();
Now I want that instead of return View(); it display error message that percentage must be 100. How can I do that?

add message in viewbag
if (prc != 100)
{
ViewBag.PercentageMessage = "your error message."
return View();
}
and in view check if ViewBag.PercentageMessage is not null and empty then display message in label.
if (ViewBag.PercentageMessage != null)
{
string message = Convert.ToString(ViewBag.PercentageMessage);
if(message != "")
{
<label>#message</label>
}
}
put this code where you want to display message

Assuming the return type is ActionResult
return Content("Percentage must be 100");

string Percentage = "Percentage must be 100";
if (prc != 100)
return Json(Percentage);

Put message in ViewBag, ViewData or model and diplay it with jquery.
Something like this
ViewBag.Error = "percentage must be 100";
javascript view
var ErrorMessage = #ViewBag.Error;
jquery
if (ErrorMessage.length>0) {
$("#divError").show().html(ErrorMessage);
}

Related

C# use field 1 value if field 2 empty

I am running through a set of records using a for each loop, and also doing simple checks to ensure that good data is inserted into a database table.
Sometimes the dataset can be missing the LegistarID value, the change I need to do in my code, is to add a check for LegistarItem,
if the value of LegistarID is missing, but the AgendaItem value is not, then assign the value of AgendaItem to LegistarID
if LegistarId is missing, and there is also no AgendaItem value, then return a message to the user, to let them know that these values need to be present in the dataset they are trying to import.
I know it does not sound complex, but I am having a hard time making this change successfully. I need a bit of help if possible, please.
Here is my code as I currently have it:
if (ModelState.IsValid)
{
using (Etities db = new Entities())
{
foreach (var i in meeting)
{
if (i.MeetingID == 0)
{
message = string.Format("This file is missing the Meeting ID value of at least 1 record. \n Verify that the data you are trying to upload meets the criteria, and then try to upload your file again.", i.MeetingID);
return new JsonResult { Data = new { status = status, message = message } };
}
else
{
// development
var compositeKey = db.MeetingAgenda.Find(i.MeetingID, i.AgendaItem);
if (compositeKey == null)
{
// Add new
// development
db.MeetingAgenda.Add(i);
//
}
else
{
// Serves as an update, or addition of a previously imported dataset
db.Entry(compositeKey).CurrentValues.SetValues(i.MeetingID);
db.Entry(compositeKey).State = EntityState.Modified;
}
}
}
db.SaveChanges();
status = true;
}
}
else
{
message = string.Format("Please, verify that the file you are trying to upload is correctly formatted, and that the data it contains, meets the expected criteria, then click the upload button again. \n Thank you!");
return new JsonResult { Data = new { status = status, message = message } };
}
I think that part of the code I need is something like this:
else if (i.LegistarID == 0 and i.AgendaItem != 0)
{
i.LegistarID = i.AgendaItem
}
I just am unsure how in the current code place it.
I would check all rows before returning a result.
if (ModelState.IsValid) {
var errors = new List<string> ();
var rowCounter = 1;
using (Etities db = new Entities ()) {
foreach (var i in meeting) {
if (i.MeetingID == 0) {
// Let the user know this row is bad
errors.Add ($"Row {rowCounter}: This file is missing the Meeting ID. Verify that the data you are trying to upload meets the criteria, and then try to upload your file again.");
}
// Check if LegistarID is missing
if (i.LegistarID == 0) {
// Check if Agenda Item is present
if (i.AgendaItem == 0) {
errors.Add ($"Row {rowCounter}: Meeting has no LegistarID and no Agenda Item. Please check data");
} else {
i.LegistarID = i.AgendaItem
}
}
// development
var compositeKey = db.MeetingAgenda.Find (i.MeetingID, i.AgendaItem);
if (compositeKey == null) {
// Add new
// development
db.MeetingAgenda.Add (i);
//
} else {
// Serves as an update, or addition of a previously imported dataset
db.Entry (compositeKey).CurrentValues.SetValues (i.MeetingID);
db.Entry (compositeKey).State = EntityState.Modified;
}
rowCounter++;
}
// If there are errors do not save and return error message
if (errors.Count > 0) {
return new JsonResult { Data = new { status = false, message = string.Join ("\n", errors) } };
}
db.SaveChanges ();
status = true;
}
} else {
message = string.Format ("Please, verify that the file you are trying to upload is correctly formatted, and that the data it contains, meets the expected criteria, then click the upload button again. \n Thank you!");
return new JsonResult { Data = new { status = status, message = message } };
}
The "if(i.MeetingID == 0)" else is redundant, because you are returning if the condition is met. So to avoid unneeded/confusing nesting I would rewrite the actual code (of the loop only) as:
foreach (var i in meeting)
{
if (i.MeetingID == 0)
{
message = string.Format("This file is missing the Meeting ID value of at least 1 record. \n Verify that the data you are trying to upload meets the criteria, and then try to upload your file again.", i.MeetingID);
return new JsonResult { Data = new { status = status, message = message } };
}
// development
var compositeKey = db.MeetingAgenda.Find(i.MeetingID, i.AgendaItem);
if (compositeKey == null)
{
// Add new
// development
db.MeetingAgenda.Add(i);
//
}
else
{
// Serves as an update, or addition of a previously imported dataset
db.Entry(compositeKey).CurrentValues.SetValues(i.MeetingID);
db.Entry(compositeKey).State = EntityState.Modified;
}
}
Then, I would add the new condition in between the MeetingID = 0 check and the rest of the code, like this:
foreach (var i in meeting)
{
if (i.MeetingID == 0)
{
message = string.Format("This file is missing the Meeting ID value of at least 1 record. \n Verify that the data you are trying to upload meets the criteria, and then try to upload your file again.", i.MeetingID);
return new JsonResult { Data = new { status = status, message = message } };
}
// *** New check on LegistarID and AgendaItem ***
if(i.LegistarID == 0)
{
// Is there a chance to fill LegistarID with AgendaItem?
if(i.AgendaItem != 0)
{
// Yes, fill it and then let the rest of the code flow peacefully.
i.LegistarID = i.AgendaItem
}
else
{
// No way: I must stop the procedure here and warn the user about this.
// return "these values need to be present in the dataset they are trying to import."
}
}
// development
var compositeKey = db.MeetingAgenda.Find(i.MeetingID, i.AgendaItem);
if (compositeKey == null)
{
// Add new
// development
db.MeetingAgenda.Add(i);
//
}
else
{
// Serves as an update, or addition of a previously imported dataset
db.Entry(compositeKey).CurrentValues.SetValues(i.MeetingID);
db.Entry(compositeKey).State = EntityState.Modified;
}
}

How to fix 'Nullable object must have a value' for a string using TempData

I am checking to see if a user has payment data associated with them and to display that data if so.
I've tried redefining 'paymentMessage' in various ways to no avail. I am getting the error that paymentMessage must have a value.
public ActionResult Index() {
string paymentMessage = (string)TempData["payment_result"];
PublicBasicDetailsViewModel viewModel = new PublicBasicDetailsViewModel();
viewModel.Patron = Datasource.GetPatron(CurrentUser.PatronId.Value);
viewModel.Transactions = Datasource.GetPatronTransactionList(viewModel.Patron.PatronID);
viewModel.IsFirstLogin = CurrentUser.IsFirstLogin;
if (CurrentUser.IsFirstLogin) {
string userIdent = HttpContext.User.Identity.GetUserId();
Datasource.SetFirstLogin(userIdent);
}
if (paymentMessage == null) {
viewModel.HasPaymentResult = false;
return View(viewModel);
}
else if (paymentMessage == "SUCCESS") {
viewModel.HasPaymentResult = true;
return View(viewModel);
}
else {
viewModel.HasPaymentResult = true;
viewModel.Errors = paymentMessage;
return View(viewModel);
}
}
This is the error message appearing when I log in as a user
Exception Details: System.InvalidOperationException: Nullable object
must have a value.
Source Error: Line 57: string paymentMessage =
(string)TempData["payment_result"];
Tempdata has a lifetime of two actions.
https://www.codeproject.com/Tips/827059/Data-Passing-Mechanism-in-MVC-Architecture

How to highlight the duplicate value in kendo grid

This is my logic to prevent duplicate values in the controller
public ActionResult ProviderType_Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProviderTypeMasterViewModel> ProviderTypeMasterList)
{
var results = new List<ProviderTypeMasterViewModel>();
try
{
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Start");
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
var provd = _context.TblProviderTypeMasters.Where(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName).ToList();
if (provd != null && provd.Count() == 0)
{
if (ProviderTypeMasterList != null && ModelState.IsValid)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
else
{
duplicate = true;
return this.Json(new DataSourceResult
{
Errors = "my custom error"
});
}
}
_logger.LogInformation("ProviderTypeMastersController ProviderType_Create Complete");
}
catch (Exception e)
{
_logger.LogError("ProviderTypeMastersController ProviderType_Create Failed - " + e.Message);
}
return Json(results.ToDataSourceResult(request, ModelState));
}
I show the error in an alert message using the error event of the kendo grid in my view. Now I need help on these two things.
1.) Is there any other way I could show the error message without an alert message. Like a label? If so where should I hide the label after the duplicate is removed?
2.) I want to highlight the particular value of the grid in which the user has entered the duplicate value. A change like changing the particular grid value to red when id is duplicate and remove the red color when the user changes the duplicate value to a unique value.
I am a beginner and I am stuck here. Can anyone help me with this? Thanks
Just add your error to ModelState:
public JsonResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<ProviderTypeMasterViewModel> ProviderTypeMasterList)
{
if (ModelState.IsValid)
{
foreach (var ProviderTypeMaster in ProviderTypeMasterList)
{
TblProviderTypeMaster ptm = new ProviderTypeMasterViewModel().ToModel(ProviderTypeMaster);
if (_context.TblProviderTypeMasters.Any(p => p.ProviderTypeName == ProviderTypeMaster.ProviderTypeName))
{
ModelState.AddModelError("ProviderTypeName", "ProviderType already exists");
}
else
{
if (ProviderTypeMasterList != null)
{
string userID = GetUserID();
providerTypeMasterService.SaveProviderTypeMaster(ProviderTypeMaster, userID);
}
}
}
}
}
return Json(results.ToDataSourceResult(request, ModelState));
In order to format Kendo Grid Column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?.
UI for Javascript:
{
field: "EmployeeName", type: "string", width: "55px", title: "Employee Name",
template: "#= GetEditTemplate(data) #"
}
UI for MVC:
...
columns.Bound(t => t.EmployeeName).Title("Status Name").Template(#<text></text>)
.ClientTemplate("#= GetEditTemplate(data)#").Width("55px");
...
Here is the method used in the example:
<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
var html;
if (data.StatusID == 1) {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-success'>" +
data.EmployeeName
+ "</span>"
);
}
else {
html = kendo.format(
//"<a class=\"k-button\" href='" + '#Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a> ",
"<span class='text-danger'>Cancel</span>"
);
}
return html;
}
</script>

DropDownListFor() and 500 Errors

I am getting a 500 error when I post my AJAX form via clicking the submit button. The controller that handles the AJAX post is getting the data fine but when I return the Partial View, via this line, I am getting the 500:
return PartialView("_SiteSurveyNewClubTeam", model);
The reason I am returning the partial back instead of a HTTP status code is because if I don't, one of my dynamic dropdowns comes back unpopulated. Maybe I am pinting myself into a corner, here.
The data types supplied in the offending DropDownListFor() I believe are correct and in the right order: (string, IList<SelectListItem>)
Error
The ViewData item that has the key 'DistrictSelected' is of type 'System.String'
but must be of type 'IEnumerable<SelectListItem>'.
View Model Declarations
public IList<SelectListItem> DistrictSelect { get; set; }
public string DistrictSelected { get; set; }
Source of the Error is this line in my View
<span class="formColumn2">#Html.DropDownListFor(model => model.DistrictSelected, Model.DistrictSelect)</span>
Not sure why I am getting this. Any ideas?
Thanks
Here is the code that processes the AJAX form post
[HttpPost]
public ActionResult ProcessFormANewClubTeam(FormANewClubTeamViewModel model)
{
var httpStatus = HttpStatusCode.BadRequest;
var cosponsors = new List<NewClubSponsor>();
var errorMessages = new StringBuilder();
var tasks = new NewClubBuilderTasks();
var clubKeyNumber = tasks.GetClubKeyNumber();
var masterCustomerId = tasks.GetMasterCustomerId();
bool exceptionRaised = false;
if (ModelState.IsValid)
{
if (model.NewClub_Id > 0)
{
//Load the entity to be partially-updated
NewClub newClub = db.NewClubs.Single(nc => nc.Id == model.NewClub_Id);
//Set the values for the fields to be updated
newClub.District = model.DistrictSelected;
newClub.Division = model.DivisionSelected;
newClub.Region = Utility.Personify.GetRegionFromDistrict(newClub.District);
newClub.ClubCounselorMasterCustomerId = model.ClubCounselorMasterCustomerId;
newClub.ClubCounselorContact = model.ClubCounselorContact;
newClub.ClubCounselorEmail = model.ClubCounselorEmail;
newClub.ClubCounselorPhone = model.ClubCounselorPhone;
newClub.DateUpdated = DateTime.Now;
try
{
//Execute the UPDATE
var dbResult = db.SaveChanges() > 0;
httpStatus = HttpStatusCode.OK;
}
catch (SqlException ex)
{
//Catch exceptions here
}
// return new HttpStatusCodeResult((int) httpStatus);
return PartialView("_SiteSurveyNewClubTeam", model);
} else {
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new {x.Key, x.Value.Errors})
.ToArray();
return new HttpStatusCodeResult((int) httpStatus);
}
}
You have to repopulate your select list items in your DistrictSelect list in the post action. Your viewmodel that was posted has DistrictSelect as null, this is why you are getting that exception when you render your partial.

MVC 3 Image field validation

I have a form that I upload two images. I want to do validation on these images, such as image size and I want to be able to check if the image field are not left blank.
public ActionResult Create(NewsViewModel newsViewModel, IEnumerable<HttpPostedFileBase> files)
{
try
{
//more code here
var originalFile = string.Empty;
IList<string> images = new List<string>(2);
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null) originalFile = Path.Combine(Server.MapPath(upload_path), DateTime.Now.Ticks+"_ "+ fileName);
file.SaveAs(originalFile);
images.Add(originalFile);
}
}
if (images.Count == 2)
{
newsViewModel.News.Thumbnail = images[0] ?? "";
newsViewModel.News.Image = images[1] ?? "";
}
//more code here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
How can i send response back to the form after checking the image sizes and find out that they are not valid?
or if images.count is not 2, how do i validate that?
any ideas ?
You could add an error to the ModelState and then re-show the same view, something like this:
ModelState.AddModelError(string.Empty, "The image is not valid becuase...");
return View(newsViewModel)
Then in the view if you have a ValidationSummary your validation error message would be shown on it (the first argument is the "key" which matches to the control ID to show the message next to usually, which is why it is String.empty here but maybe you have a control you want it to be associated with).

Categories