MVC 4 Displaying error message - asp.net-mvc

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>
}

Related

error from the controller not coming to view in MVC

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
}

Error message position in mvc razor

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).

ViewBag In ASP.NET MVC

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...

Show a Message in MVC using TempData

i want to show a message in asp.net mvc. for this, i create a partial view. name of this partial view is _feedback. in body of this partial view i write this codes.
#model MyProject.SharedTools.OperationStatus
#if (Model != null)
{
if (Model.IsSuccess)
{
#:Model.Message;
}
else
{
#:Model.Message;
}
}
i put this code in _layout file:
#Html.Partial("_feedback")
and when i want to see a message from controller, using this code:
operationStatus = _provinceRepository.Save();
if (operationStatus.IsSuccess)
{
TempData["OperationStatus"] = operationStatus;
return RedirectToAction("Index");
}
but i give this error:
The model item passed into the dictionary is of type 'MyProject.Models.ProvinceModel', but this dictionary requires a model item of type 'MyProject.SharedTools.OperationStatus'.
Make sure that you have passed the correct model that your partial is expecting:
#Html.Partial("_feedback", Model.SomePropertyOfTypeOperationStatus)
If you do not specify a model as second argument to the Html.Partial helper, then it will automatically pass the model of the current view (which in your case is of type MyProject.Models.ProvinceModel) and that's why you are getting the error : your partial expects a model of type MyProject.SharedTools.OperationStatus.
Also it is not quite clear where you are using the TempData value that you stored in your controller inside your partial. Maybe it should be something like this:
#model MyProject.SharedTools.OperationStatus
#if (Model != null)
{
#TempData["OperationStatus"]
}
or didn't you just mean to display directly the value you stored in TempData in your partial without using a model?
#TempData["OperationStatus"]

Pass Value from View To Controller in Asp.net MVC

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.

Resources