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>
Related
so I have 3 fields that combines into 1 string and I'm currently fixing the validation so the question is how can i identify a certain textbox that is empty and the user needs to fill it up before he/she can proceed i tried this
if(string.IsNullOrEmpty(txtEYear.Text) || string.IsNullOrEmpty(txtECat.Text) || string.IsNullOrEmpty(txtEID.Text))
{
MessageBox.Show("Please fill in the missing fields");
}
Try this one.When any filed is empty focus the required field.
string message = string.empty;
message = "Please fill the ";
if(string.IsNullOrEmpty(txtEYear.Text))
{
message = message + " txtEYear ";
txtEYear.Focus();
}
if(string.IsNullOrEmpty(txtECat.Text))
{
message = message + " txtECat";
txtECat.Focus();
}
if(string.IsNullOrEmpty(txtEID.Text))
{
message = message + " txtEID";
txtEID.Focus();
}
MessageBox.Show(message+" Fields");
For that you have to use separate loop and form the message something like this:
bool isValidated = true;
StringBuilder message= new StringBuilder("Please fill the following fields: ");
if(string.IsNullOrEmpty(txtEYear.Text)
{
message.Append("Year");
isValidated = false;
}
if(string.IsNullOrEmpty(txtECat.Text))
{
message.Append("txtECat");
isValidated = false;
}
if(string.IsNullOrEmpty(txtEID.Text))
{
message.Append("ID");
isValidated = false;
}
// check all fields are valid
if(isValidated)
{
// Continue
}
else
{
MessageBox.Show(message.ToString());
}
When I hover over the Index it has a red line underneath and says
'UnauthEnquiryController.index(UnauthenticatedEnquiryViewModel)': not all code paths return a value.
I was just wondering what was the fix to this?
[HttpPost]
public ActionResult Index(UnauthenticatedEnquiryViewModel unauthenticatedEnquiryViewModel)
{
//unauthenticatedEnquiryViewModel.EnquiryType;
//NEED TO ADD A METHOD THAT SENDS FILE TO CRM HERE
if (ModelState.IsValid)
{
if (1 == 0) //take off
{
string fromAddress = WebConfigurationManager.AppSettings["FromEmail"]; //gets email from web.config file
//var toAddress = new MailAddress(); //need to get this from crm
var enquiry = DataAccessEnquiry.GetEnquiryCategoryEmail(unauthenticatedEnquiryViewModel.EnquiryType); //gets the to address based on CRm
string UnauthEmailSubject = WebConfigurationManager.AppSettings["UnauthEmailSubject"]; //gets subject from web.config file
MailMessage mailMessage = new MailMessage(fromAddress, enquiry.Email); //put to address frrom variable declared above
mailMessage.Subject = UnauthEmailSubject;
StringBuilder mailbuilder = new StringBuilder();
mailbuilder.AppendLine("First name: " + unauthenticatedEnquiryViewModel.FirstName);
mailbuilder.AppendLine("Last name: " + unauthenticatedEnquiryViewModel.LastName);
mailbuilder.AppendLine("Communication: " + unauthenticatedEnquiryViewModel.CCommmunication);
mailbuilder.AppendLine("Email: " + unauthenticatedEnquiryViewModel.Email);
mailbuilder.AppendLine("Confiirmation of email: " + unauthenticatedEnquiryViewModel.ConfirmEmailAddress);
mailbuilder.AppendLine("Mobile telephone No: " + unauthenticatedEnquiryViewModel.MobileTelephoneNo);
mailbuilder.AppendLine("Confiirmation of mobile telephone no: " + unauthenticatedEnquiryViewModel.ConfirmMobileTelephoneNo);
mailbuilder.AppendLine("Alternative telephone no: " + unauthenticatedEnquiryViewModel.AlternativeTelephoneNo);
mailbuilder.AppendLine("Confiirmation of alternative telephone no: " + unauthenticatedEnquiryViewModel.ConfirmAlternativeTelephoneNo);
mailbuilder.AppendLine("I am a: " + unauthenticatedEnquiryViewModel.Profession);
mailbuilder.AppendLine("Enquiry Type: " + unauthenticatedEnquiryViewModel.EnquiryType);
mailbuilder.AppendLine("Your message: " + unauthenticatedEnquiryViewModel.YourMessage);
if (unauthenticatedEnquiryViewModel.File != null) // this finds overall null
{
foreach (var file in unauthenticatedEnquiryViewModel.File) // loop through every File
{
if (file != null) //Finds induvidual null
{
var extension = new FileInfo(file.FileName).Extension.ToUpper();
mailMessage.Attachments.Add(new Attachment(file.InputStream, file.FileName));
}
}
}
mailMessage.Body = mailbuilder.ToString();
SmtpClient smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
}
return View("Unauthsuccess", unauthenticatedEnquiryViewModel);
}
unauthenticatedEnquiryViewModel.Professions = DataAccessEnquiry.GetProfessionUnauthenticated();
unauthenticatedEnquiryViewModel.EnquiryTypes = new List<EnquiryType>();
}
[HttpPost]
public ActionResult Index(UnauthenticatedEnquiryViewModel unauthenticatedEnquiryViewModel)
{
//unauthenticatedEnquiryViewModel.EnquiryType;
//NEED TO ADD A METHOD THAT SENDS FILE TO CRM HERE
if (ModelState.IsValid)
{
...
return View("Unauthsuccess", unauthenticatedEnquiryViewModel);
}
unauthenticatedEnquiryViewModel.Professions = DataAccessEnquiry.GetProfessionUnauthenticated();
unauthenticatedEnquiryViewModel.EnquiryTypes = new List<EnquiryType>();
//THIS path doesn't return value.
//HERE return somethig
}
You return value only if if (ModelState.IsValid) is true but what want you return if this is false?
Here you have created a condition,
if(ModelState.Isvalid)
{
{// LOTS OF CODE}
return View(....);
}
But if
ModelState.Isvalid == false
is true then the function wouldn't return anything
You are returning value in if condition only that's way its saying. You must have to return after if condition as well
Basically on the master page I have a method which returns a "campaign" with the params of a unique Id and a user Id. Which works fine until I click a button in a derived page.
The problem is when I click a button in a derived page the method in the master page returns "null". Even when debugging I see the correct params.
EDIT// The Method that returns null:
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
Master page code:
protected void Page_Load(object sender, EventArgs e)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = User.GetLoggedInUser(securityToken);
if (user != null)
{
var convertedCampaignId = Request.QueryString["cid"];
//If the querystring exists process ELSE force
if (!string.IsNullOrWhiteSpace(convertedCampaignId))
{
using (var campaignRepository = new CampaignRepository())
{
var campaign = campaignRepository.GetCampaignById(convertedCampaignId, user.UserId);
//Does the campaign exist from the passed in query string,
if (campaign != null)
{
ccid = "'" + campaign.ConvertedCampaignId + "'";
//Build Navigation
StringBuilder sbNav = new StringBuilder();
string nav = KTO.Common.Reader.ReadFile("/templates/html/side-nav.html");
sbNav.AppendLine(nav.Replace("{convertedCampaignId}", campaign.ConvertedCampaignId));
ltlNavItems.Text = sbNav.ToString();
ltlCampaignName.Text = "Campaign: " + "<strong>" + campaign.Name + "</strong>";
//Get campaigns for dropdown
IEnumerable<Campaign> campaigns = campaignRepository.GetCampaigns(user.UserId);
StringBuilder sbCampaigns = new StringBuilder();
string strCampaigns =
"<li title='{campaignName}' data-cid='{convertedCampaignId}' class='js-campaign-item'>" +
"<p class='name-message'><a href='/panel/c/{convertedCampaignId}/' class='campaign-lnk'>{campaignName}</a>" +
"</p>" +
"</li>";
foreach (var c in campaigns)
{
sbCampaigns.AppendLine(strCampaigns.Replace("{convertedCampaignId}", c.ConvertedCampaignId)
.Replace("{campaignId}", c.CampaignId.ToString())
.Replace("{campaignName}", c.Name));
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
}
else
{
Response.Redirect("/notifications/404/");
}
}
else
{
Response.Redirect("/login/");
}
}
Derived page logic:
protected void btnInviteUsers_Click(object sender, EventArgs e)
{
if (txtEmail.Text.Trim() != "")
{
if (txtEmail.Text.Trim().Length < 75)
{
if (Common.Email.IsValidEmail(txtEmail.Text.Trim()) == true)
{
string securityToken = "";
if (HttpContext.Current.Request.Cookies["SecurityToken"] != null)
{
securityToken = HttpContext.Current.Request.Cookies["SecurityToken"].Value.ToString();
}
var user = Business.Entity.User.GetLoggedInUser(securityToken);
if (user != null)
{
try
{
using (var userRepo = new UserRepository())
{
var userInSystem = userRepo.UserExists(txtEmail.Text.Trim().RemoveHtml());
if (userInSystem == true)
{
ltlReturnMessage.Text = "Unfortunately we cannot send the request, as the user already exists.";
}
else
{
//Craft querystring
string encryptedEmail = user.EncryptedEmail;
int uid = user.UserId;
string userInviteHTML = Common.Reader.ReadFile("/templates/emails/user-invite.html");
StringBuilder sb = new StringBuilder();
sb.AppendLine(userInviteHTML.Replace("{link}", "http://localhost:52447/_user-invite/?inor-t-em=" + encryptedEmail + "&inor-d=" + uid.ToString()));
Common.Email.SendMail(txtEmail.Text.Trim(), "", "", user.FirstName + " " + user.LastName + " invited you to join x", sb.ToString());
ltlReturnMessage.Text = "Invite sent!";
}
}
}
catch
{
ltlReturnMessage.Text = "Problem sending invite, please try again.";
}
}
}
else
{
ltlReturnMessage.Text = "Are sure that's an email address? Please try again.";
}
}
else
{
ltlReturnMessage.Text = "Email Address must not exceed 75 characters.";
}
}
else
{
ltlReturnMessage.Text = "Email Address required.";
}
}
Please consider the method does return a "campaign" on any page but just not when the page posts back.
After scrutinising every last line, I noticed that my query string was duplicated. When the button click event fired from my derived page it would post back thus running my logic on the master page. I would assume it played havoc with url-rewriting.
I fixed this by adding
frmInviteUser.Action = Request.RawUrl;
within the page_load of my derived page, which would force the request of the url and not postback to the master.
This is why I was getting a null on the method, the param passed was duplicated.
Regards,
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);
}
I am not sure what I am doing wrong here.
I have a list where I am creating hyperlinks. I need to point the user to the right page first though so I do a getJson.
I have the following code in my .cshtm file:
$.getJSON('/Home/GetLocType', { "locId": loc.locId },
function(result) {
result = Json.stringify(result);
if(result == '1')
{
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
}
else
{
$('<li><a id=' + loc.locId + ' href="/DataEntry/PForm" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
}
});
I have the following code in the controller:
private JsonResult GetLocType(int locId)
{
int locationId = Convert.ToInt32(locId);
var result = db.Locations.Where(a => a.LocID == locationId).Select(a => a.TypeId);
return Json(result);
}
The problem I am facing is that the Json method never gets called.
Your controller method is declared as private - As such it would not be accessible.
Change it to public.
Secondly, you should activate allow get - Details on why this is not set by default see - Why is JsonRequestBehavior needed?
public JsonResult GetLocType(int locId)
{
int locationId = Convert.ToInt32(locId);
var result = db.Locations.Where(a => a.LocID == locationId).Select(a => a.TypeId);
return Json(result, JsonRequestBehavior.AllowGet);
}