display error message on front-end asp.net mvc - html

How do I display a message on a div <div asp-validation-summary="All" class="text-danger"></div> when I am sending a message from the back-end?
[HttpPost]
public IActionResult Signup(Signup signup)
{
var result = DBGetCls.GetList("SELECT * FROM Usertable WHERE Email = '{0}' ", signup.Email);
if (result.Count > 0)
{
object notFound = new { message = "Email has been used!" };
return BadRequest(notFound);
}
So my form would look like this:
<div id="signup">
<form asp-action="Signup">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="field-wrap">
<label asp-for="FullName" class="control-label active highlight">Name :</label>
<input asp-for="FullName" class="form-control" />
</div>
.
.

In your frontend MVC controller, you can add errors to the model state. These will be rendered in the validation summary. So when the backend answers with BadRequest, add an error manually.
ModelState.AddModelError("PropertyNameInViewModelToBeHighlighted",
"Error message to be shown in validation summary");
Some teams also build custom infrastructure to wrap the backend calls, catch any errors, extract the error message, and add it to the ModelState automatically.
See also What is the ModelState?

Related

ERROR TypeError: Cannot read property 'name' of undefined angular

I'm developing an app using Laravel as backend and Angular as frontend. To login and register I'm trying to use JWT but when I try to register using the register form I get the following error: "ERROR TypeError: Cannot read property 'name' of undefined".
register.component.html
<form #registerForm=ngForm (ngSubmit)="onSubmit()">
<div class="form-group row mx-auto">
<label for="inputName3" class="col-md-6 col-form-label">Name</label>
<div class="col-md-12">
<input type="text" name="name" class="form-control"
placeholder="Name" [(ngModel)]="form.name" required>
<div class="alert alert-danger mt-2" [hidden]="!error.name">
<i class="fa fa-times-circle"></i> {{error.name}}
</div>
</div>
</div>
...
</form>
register.component.js
export class RegisterComponent implements OnInit {
public form = {
name: null,
email: null,
password: null,
password_confirmation: null
};
constructor(private http: HttpClient) { }
onSubmit(){
return this.http.post('http://localhost/api/auth/register',
this.form).subscribe(
data => console.log(data),
error => this.handleError(error)
);
}
ngOnInit() {
}
}
In the template, your test [hidden]='!error.name' is not valid because the variable error is not defined in the controller (.ts).
You should define error property with type object in the component.
because Angular expects an object called error with name key.
If you wait error from the backend or you need a quick solution just put ? (question mark) after error word in HTML like: [hidden]='!error?.name'.
This will make Angular check for error variable before checking for name property.

How to create single page search form with ajax in MVC Razor

I'm a beginner in the ways of MVC / Razor... Basically I have 2 pages just for showing a search result from an API that I'm consuming with Json.
Index.cshtml: (Just a form)
#model ConsultaInterna.Models.SearchApi
<div class="jumbotron">
<h2>Consulta Interna</h2>
Placa
#using (Html.BeginForm("Search", "Home"))
{
<input asp-for="Model.Name" class="form-control" name="name" id="txtName" />
<input class="form-control" type="submit" id="ok" />
}
and Search.cshtml (Which also have the form. I want to leave just this page, right now I can't because if I load directly from Search.cshtml it gives me an error like
"Unexpected character encountered while parsing value: <. Path '', line 0, position 0. " (Obviously because I'm trying to load labels with a null search)
this is Search.cshtml
#model ConsultaInterna.Models.SearchApi
<div id="loader" class="spinner" style="display:none">OIE</div>
<div class="header formPesquisa">
#using (Ajax.BeginForm("Search", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<input placeholder="Placa" asp-for="Model.Name" name="name" id="txtName" width="30" />
<input class="pesquisa" type="submit" id="enviar" value="Ok" />
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
ALSO Important, the Ajax form isn't working properly... the loader won't show up.
You need to move your loader div into the Ajax.BeginForm.
You need also need to add the resultado div to display your result.
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<div id="loader" class="spinner" style="display:none">OIE</div>
<input placeholder="Placa" asp-for="Model.Placa" class="pesquisa placa" maxlength="7" name="placa" id="txtPlaca" width="30" />
<input placeholder="CPF" asp-for="Model.CPF" class="pesquisa cpf" maxlength="11" name="cpf" id="txtCPF" />
<input class="pesquisa" type="submit" id="enviar" value="Enviar" />
<div id="resultado"></div>
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
</div>
You also need to make sure you have added the relevant reference to the specific unobtrusive ajax library. As an example:
BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.validate*"));
_layout.cshtml
#Scripts.Render("~/bundles/jqueryval")
Example controller action
[HttpPost]
public ActionResult Search(string placa, string cpf)
{
return new JsonResult { Data = "found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Match Error with Meteor.callLoginMethod

I'm trying to send my login with :
'submit form': function(event) {
event.preventDefault();
event.stopPropagation();
var loginRequest = {
username: event.target.loginUsername.value.toLowerCase(),
password: event.target.loginPassword.value,
};
var callback = function(response) {
Session.set('showLoading', false);
};
Session.set('showLoading', true);
Accounts.callLoginMethod({
methodArguments: [loginRequest],
userCallback: callback,
});
},
But I get an error and I can't figure out what is the thing that create this error :
Exception while invoking method 'login' Error: Match error: Unknown key in field username
...
Sanitized and reported to the client as: Match failed [400]
I founded some informations in the web but nothing that really helped me. I think it's generated when I call Accounts.callLoginMethod
My form looks like this:
<form>
<div class="row">
<div class="input-field col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<label for="loginUsername">Username</label>
<input id="loginUsername" type="text" class="form-control" disabled="{{showLoading}}" required>
<br>
<label for="loginPassword">Password</label>
<input id="loginPassword" type="password" class="form-control" disabled="{{showLoading}}" required>
</div>
</div>
<br>
{{#if showLoading}}
{{> loading}}
{{else}}
<div class="text-center">
<button type="submit" class="btn btn-primary">Login</button>
</div>
{{/if}}
</form>
Someone could help me or know what is creating this error ?
Here is my 2 cents. Accounts.callLoginMethod is technically not a documented API function and in theory could change in any future Meteor release. Since it's not documented, the errors that it returns are not well defined and could be confusing.
Since you are just doing password authentication, I would recommend you use Meteor.loginWithPassword(user, password, [callback]) instead. At least this way you have a set of API documentation to fallback on if you get errors such as this (it also returns more specific errors when something goes wrong).
Try switching​ and see if you still receive an error output. If so the error will be one of the below error messages and you can better debug to see what's going on.
“Unrecognized options for login request [400]” if user or password is undefined.
“Match failed [400]” if user isn’t an Object or String, or password isn’t a String.
“User not found [403]” if the email or username provided in user doesn’t belong to a registered user.
“Incorrect password [403]” if the password provided is incorrect.
“User has no password set [403]” if user doesn’t have a password.
If you encounter one of the above errors, then do console.log(username) and make sure it is a string or object with the value that you are expecting.

ASP.NET MVC Redirect to same page after submit button is clicked

some friends and I have started a team project but we are stuck at this point. We made a function of the site to add comments under every post. The problem is that when submit is clicked it adds the comment but doesn't refresh the page which causes some problems. The author stays "anonymous" and when refresh button is clicked it shows an alert:
The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you wish to continue?
However, if we just type the URL again and click ENTER everything is good: the author shows up and the comment appears only once. So the only solution for us is to redirect to the same page. Here is the form:
<div style="text-align: left">
<div><i>Leave your comment</i>
</div>
<form method="post">
<fieldset>
<p>
<textarea rows="10" class="form-control" type="text" id="1" name="commentText" style="height: 100px"></textarea>
</p>
<p>
<input type="submit" name="buttonSubmit" onclick="redirect" value="Add comment" class="btn btn-default" style="" />
</p>
</fieldset>
</form>
</div>
This is how the comments are printed on the page:
<h3>Comments</h3>
<br>
<div>
#foreach (var comment in ViewBag.Comments) {
<section class="row">
<article class="post col-md-12">
<div class="about">
Posted on <i>#comment.Date</i>
#if (comment.AuthorId != null) { #: by <i>#comment.Author.FullName</i>
}else { #: by <i>anonymous</i>
}
</div>
<div class="body">#comment.Text</div>
</article>
</section>
}
</div>
Thanks in advance!
Use the #Ajax.BeginForm() helper.
In the AjaxOptions(), you'll want to set the Httpmethod to "Post", InsertionMode.InsertBefore (or After depending on where you want new comments), and UpdateTargetId = "your-comment-div".
You'll need to include jquery.unobtrusive-ajax.js so the Ajax helper works correctly. You can use the nuget package manager to pull it in. Be sure to add it to your jquery bundle.
Then, you need to create the post action in your controller to accept the comment params and return a partial view.
Doing thIs keeps the Ajax confined to a razor helper and controller method.
View:
#using (Ajax.BeginForm("AjaxAddComment",
"MyController",
/* route params */,
new AjaxOptions()
{
InsertionMode = InsertionMode.InsertBefore,
UpdateTargetId = "commentsDiv",
HttpMethod = "Post"
}, htmlAttributes: new { /* ... */ }))
{
<div class="form-horizontal">
#* comment form... *#
</div>
}
...
<div id="commentsDiv">
<div class="comment">...</div>
<div class="comment">...</div>
</div>
Controller:
[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<PartialView> AjaxAddComment(string comment, /*...other params*/)
{
var newComment = ... // comment viewModel
// add comment to db
await db.SaveChangesAsync();
return PartialView("_CommentPartial", newComment);
}
_CommentPartial:
<div class="comment">
...
</div>

How to make Razor not display special characters as html

The page I'm working on displays content from a database in readonly input box. My problem is that it's displaying any special characters as the html code (ie: & displays as &). How do you get the code to display properly?
I'm using QuerySingle to connect to the database, don't know if that makes a difference. I'm new to using Razor. Any help is much appreciated.
Code in question:
var queryloan = "SELECT * FROM loans WHERE LoanId = #0";
var queryloandata = db.QuerySingle(queryloan, queryformstatus_submitted.doc_loanid);
<form class="jotform-form" action="submit-form.cshtml?isadmin=#(isadmin)&loanid=#(loanid)" method="post" name="form_30905105572145" id="30905105572145" accept-charset="utf-8">
<input type="hidden" name="formID" value="30905105572145" />
<input type="hidden" name="doc_id" value="#doc_id" />
<div class="form-all">
<ul class="form-section">
<li id="cid_3" class="form-input-wide">
<div class="form-header-group">
<h2 id="header_3" class="form-header">
Borrower Sources & Uses Summary
</h2>
#if (queryformstatus_submitted.doc_approval == "Pending Approval" || queryformstatus_submitted.doc_approval == "Approved")
{
<text><br />
<br />
<div class="error">
This form has already been submitted and cannot be edited. It is for reference only.</div></text>
}
#if(userid != queryformstatus_submitted.doc_userid){
<text><br/><br/><div class="error">You may not edit this form. It is for reference only.</div></text>
}
</div>
</li>
<li class="form-line" id="id_4">
<label class="form-label-left" id="label_4" for="input_4">
1. Property Name:
</label>
<div id="cid_4" class="form-input">
<input type="text" class=" form-textbox" id="input_4" name="q4_1Property" size="40" value="#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)"/>
</div>
</li>
I'm not sure but I believe it may be something in this helper function that's causing the html code:
#helper checkEmptyPreFill(IEnumerable<dynamic> queryinputvalue, string field_id, string defaultval, int cloned = 0) {
var reqValue = queryinputvalue.FirstOrDefault(r => r.field_name.Equals(field_id));
var return_value = "";
if(reqValue != null){
return_value = reqValue.field_data;
} else {
return_value = defaultval;
}
if(cloned == 1){
return_value = "";
}
#return_value
}
The razor helper returns a HelperResult object so you'll have to convert it to a string before you can call HtmlDecode on it. Replace:
#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)
with the following:
#HttpUtility.HtmlDecode(Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName).ToString())
I would also suggest that you move some of the logic and data access code out of your view and into a controller but this should give you the result that you'e after.