if (user.UserName == DbData.UserName && DbData.Password.Equals(user.Password, tringComparison.CurrentCultureIgnoreCase))
{
//redirect to main page //this is working fine
}
else {
ModelState.AddModelError("Error", "Username/Password not matching");
ViewBag.Message = ModelState["Error"].Errors[0].ErrorMessage;
return View();
}
and in View i wrote
#if(ViewBag.Message != null){
ViewBag.Message
}
but the error in the viewbag is not coming on the view
That's normal, if you check the TempData["Error"] in the immediate window, you'll see that it's null.
You need to give something to the view bag to get something in the view side.
UPDATE:
This will give you your message (
"Username/Password not matching") that you can set it to the ViewBag.
ModelState["Error"].Errors[0].ErrorMessage
Hope this solves your problem.
For your Info:
ModelStateDictionary.AddModelError Method (String, Exception):
Adds the specified model error to the errors collection for the model-state dictionary that is associated with the specified key.
from ModelState.AddModelError
UPDATE:
To display the message in the View use the # sign before the ViewBag.Message
#if (!string.IsNullOrWhiteSpace(ViewBag.Message))
{
#ViewBag.Message
}
Related
I have a requirement where an action link with query string parameter has been implemented from a controller view say CreateFilter which navigates to a different controller say Create where I parse the query string parameter and gets the data through SP and display it in the Create View.
But I have a scenario that when the SP doesn't return any data then the Create View shouldn't render and the user should be able to see the error message "No records found" in the same View where he is currently (CreateFilter).
Can any one please let me know how to achieve this scenario ? Any help would be greatly appreciated.
Thanks
Vimalkumar
Set the error message in TempData and do a redirect back to the CreateFilter action. There, you can check if that value is in TempData and display it if so.
TempData["CreateFilterError"] = "No records found";
return RedirectToAction("CreateFilter");
Then, in your CreateFilter view:
#if (TempData["CreateFilterError"] != null)
{
<p>#TempData["CreateFilterError"]</p>
}
Alternatively, you can pass something in the query string with the redirect:
return RedirectToAction("CreateFilter", { error = true });
Then, handle it much the same in your view:
#if (Request["error"] as bool? ?? false)
{
<p>No records found</p>
}
I'm trying to put custom error messages for a login and registration forms.
So far I have the form to check if there's an email already registered, if it is, it will return
Response.Write("There's already someone with that email")
But the problem with this is that the message will only appear on the top of the website.
Is there a way I could display these error messages somewhere else?
I know that in the model I could just put
[Required(ErrorMessage = "Something here")]
And then just put in the view somewhere
#Html.ValidationMessageFor(a =>a.Email)
and it will display the error there.
The code that I have for now is this:
[HttpPost]
public ActionResult Register(Registration signingUp)
{
var db = new ShareRideDBEntities();
if (ModelState.IsValid)
{
//find if email is already signed up
var FindEmail = db.tblProfiles.FirstOrDefault(e => e.PROF_Email == signingUp.Email);
//if email is not found up do this
if (FindEmail == null)
{
var Data = db.tblProfiles.Create();
Data.PROF_Password = signingUp.Password;
Data.PROF_Email = signingUp.Email;
db.tblProfiles.Add(Data);
int Saved = db.SaveChanges();
if (Saved != 0)
{
Response.Write("Registration Successful.");
}
else
{
Response.Write("There was an error.");
}
}
else
{
Response.Write("There's already an user with that email.");
return View();
}
}
else
{
Response.Write("Fill all the fields to continue.");
}
return View();
Now if I do this with an existing email it will return "There's already an user with that email." but it will be display on the top of the website.
How can I make this error message be displayed somewhere else?
I heard something with #Html.Raw() but I'm confused on how to use it.
Using this.ModelState.AddModelError method you can add any custom error message you want. If you specify property name as a key - it will be displayed by corresponding ValidationMessageFor. So in controller instead of writing to response directly do this:
ModelState.AddModelError("Email", "There's already an user with that email.");
return View();
And in view this line which you already have:
#Html.ValidationMessageFor(a =>a.Email)
will display this messagea at whatever part of the page you place it (presumably near the field for email).
I am passing my model errors via the ViewBag. In my controller I am passing a List<string> that does contain values (_modelErrors) to the ViewBag and then I am trying to display this in my view. When I debug in the view, my ViewBag does contain a _modelErrors dictionary with values, but my errors are not being rendered.
From my controller:
ViewBag._modelErrors = _modelErrors;
In my view I have tried all of these methods and yet no markup is rendered.
#try
{
foreach (string er in ViewBag._modelErrors)
{
Response.Write(er.ToString());
#Html.DisplayText(er)
#Html.DisplayText(er.ToString())
#er.GetType()
#er.ToString();
er.ToString();
}
}
catch(Exception e){}
That's a dirty code, dude! Take a look at #Html.ValidationSummary and #Html.ValidationMessageFor
Well, some codes here to clarify stuff:
[HttpPost]
public ActionResult MyAction(ModelClass inputModel)
{
if (ModelState.IsValid)
{
//for example we're trying to save our data to db
var result = _myRepository.saveStuff(inputModel);
if (result)
return RedirectToAction("someAction");
ModelState.AddModelError(string.Empty, "An error occured, check input data");
}
return View(inputModel);
}
Also you can specify key (which is your model field name) instead of string.Empty -> so you'l see error message under specified field (as default), but basically what people do is exluding property errors from validation summary (#Html.ValidationSummary(true)) - so you get just general errors in that field. Hope it'l help
Use this:
(string er in (List<string>)(ViewBag._modelErrors))
But was said this is bad practice. Also catching exceptions this way is so wrong...
I am trying to pass a message to another view (actually same controller) I can do it well but there is a problem for me..
I am new on web and it doesnt seem good ..
and here my c# code
if (createStatus == MembershipCreateStatus.Success)
{
string registrationMessage = "You have registered successfully";
return RedirectToAction("KurumsalGiris", new { message = registrationMessage });
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = message;
return View();
}
and here html side
#model E_Cv.Models.LogOnModel
#{
ViewBag.Title = "Kurumsal Giriş";
}
<h2>Kurumsal Giriş</h2>
<h2>#ViewBag.RegistrationMessage</h2>
<p>
Please enter your user name and password.
#Html.ActionLink("Yeni Kurum Kaydı", "KurumsalKayit")
if you don't have an account.
</p>
so I dont know how to pass value to another view with different way.. I dont want to show this kind of message on address bar and user musnt change it.
Secondly Could I do it with "Get" Method?
Why don't you just return a different view rather than redirecting? In fact, the code the posted in the first place should be posting to a controller that returns a view for a successful login.
In fact, why are you redirecting to a page that asks the user to login if they've just logged in?
Other possible options include encrypting the string in the URL, or just passing a flag in the URL that the controller translates into the corresponding string.
What you would do is instead of returning a RedirectToAction
you could return the View directly: (second parameter is a model, where you can use the same model class E_Cv.Models.LogOnModel adding a RegistrationMessage property to it)
return View("<name of the view>",
new E_Cv.Models.LogOnModel {
RegistrationMessage = "You have registered successfully"
});
or keep the data in the ViewBag like you have done:
ViewBag.RegistrationMessage = "You have registered successfully";
return View("<name of the view>");
regarding your last question, give the message is showing in your URL, you are using the GET method, if you return a View instead of a redirect, it'll avoid showing anything in the URL
You should use TempData in this scenario
if (createStatus == MembershipCreateStatus.Success)
{
TempData["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
And then in your view
#if (TempData["Message"] != null)
{
<h2>#TempData["Message"]</h2>
}
Or if you want to do it in the controller, just keep your view the same as it is at the moment and set ViewBag.RegistrationMessage in the controller
ViewBag.RegistrationMessage = TempData["Message"];
If the question is how to pass data between controllers without using the querystring, then one option is the Session object.
if (createStatus == MembershipCreateStatus.Success)
{
Session["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = (string) Session["Message"];
return View();
}
However, I agree with #Jonathan Wood below that this is not necessarily the best approach to the particular problem you are attempting to solve. Still, as a general technique, it is worth knowing about.
//
// Post: /Search/Alternativ1/txtBoxTitle)
[HttpPost]
public ActionResult Alternativ1(int txtBoxTitle)
{
SokningMedAlternativ1 test= new SokningMedAlternativ1();
if (txtBoxTitel != null)
{
var codeModel = test.FilteraBokLista(txtBoxTitel);
}
return View(codeModel);
}
Problem:
I have problem to find a solution to go back to my index page (first page when entering a website for the first time) view if txtBoxTitle has null.
My request:
How shall I enter to my index page view automatically if txtBoxTitle contains null?
You have two possibilities:
Redirect to the Index action (sending a 302 status code to the client):
return RedirectToAction("Index");
Render the Index view (the client keeps the original URL in the address bar, no redirect here):
return View("Index", someModelThatTheIndexActionExpects);
If this Index action is located on another controller you have the possibility to specify this controller name:
return RedirectToAction("Index", "Home");
and:
return View("~/Views/Home/Index.aspx", someModelThatTheIndexActionExpects);
Remark: In your example the txtBoxTitle argument is declared as System.Int32, so talking about it being or not being null just makes absolutely no sense as this is a value type which can never be null and your if condition code won't even compile as you have it currently written.