Modelstate errors not shown correctly - c#
I have a strange problem with the modelstate errors in my asp.net webapi2 (not core) being displayed only as:
\"\"
This is my controllers code:
if (!ModelState.IsValid)
{
Log.Verbose("Modelstate NOT valid");
var errorList = JsonConvert.SerializeObject((from item in ModelState.Values
from error in item.Errors
select error.ErrorMessage).ToList());
Log.Verbose("modelstate errors: " + errorList);
Log.Verbose("resulting object:" + JsonConvert.SerializeObject(computerObject));
return BadRequest("Modelstate not valid" + errorList);
}
Log.Verbose("Modelstate is valid");
return (Ok("dumped + jsonitem));
I think this worked at the beginning but now it is displaying lots of unuseful stuff:
{
"Message": "Modelstate not valid[\"\",\"\",\"\",\"\",\"\",
\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",
\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",
\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",
\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"
The ComputerOsClientComputer field is required.\"]"
}
I interted line breaks for better readability. The original result looks like this:
{
"Message": "Modelstate not valid[\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"The ComputerOs field is required.\"]"
}
While I can definately see that "The ComputerOs field is required" I don't know what all the other stuff is supposed to mean :/
Once I resolve the "ComputerOs field is required error the rest stays there. So it has to mean something.
Can anyone please enlighten me?
Thanks a lot!
Steffen
found it!
One part of my json request was malformed.
I did not post my request here because it is pretty big and I didn't know which part caused the error.
While my model states this:
public class ComputerLocalGroups
{
public string Groupname { get; set; }
public int LocalGroupId { get; set; }
}
what I sent in my json request was
{
"ComputerLocalGroupsCurrent":[{"Access Control Assistance Operators", 11}]
}
instead of:
{
"ComputerLocalGroupsCurrent":[{"Groupname":"Access Control Assistance Operators", "LocalGroupId":11}]
}
It's very odd that it causes this kind of "error message" instead of something more helpful, but it was my fault in the beginning so I can't complain :D
Related
C# ASP.Net Errors on form submission
I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it. I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this: public ActionResult Create(Vendors model) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); try { if (ModelState.IsValid) { var userId = User.Identity.GetUserId(); //var getdata = ExtendedViewModels.VendorToEntity(model); model.VendorId = Guid.NewGuid(); model.CreatedDate = System.DateTime.Now; model.CreatedBy = User.Identity.Name; model.Status = true; db.Vendors.Add(model); db.SaveChanges(); sb.Append("Submitted"); return Content(sb.ToString()); } else { foreach (var key in this.ViewData.ModelState.Keys) { foreach (var err in this.ViewData.ModelState[key].Errors) { sb.Append(err.ErrorMessage + "<br/>"); } } } } catch (Exception ex) { sb.Append("Error :" + ex.Message); } return Content(sb.ToString()); } When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this: #Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed") This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this. This is from Meta data: // // Parameters: // stark: // // FormId: // Enter Here Form ID LIKE So you have to pass = frmCreate // // DataTableId: // Which DataTable You have update after submit provide that ID // // IsCloseAfterSubmit: // Do you want to opened popup close after submit , So pass=true or false any // // SuccessMessage: // Give any Success message public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage); // // Parameters: // stark: // // FormId: // Enter Here Form ID LIKE So you have to pass = frmCreate // // DataTableId: // Which DataTable You have update after submit provide that ID // // IsCloseAfterSubmit: // Do you want to opened popup close after submit , So pass=true or false any // // SuccessMessage: // Give any Success message // // AfterSuccessCode: // Add other JQuery code if you want public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode); Thanks for our help UPDATE: I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.
I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.
RedirettoAction() doesn't takes object
I have the following method public ActionResult APLogin(int userId, int courseId, string authToken) { try { // // To be varified from Assessment platform, will be implemented later. // //Make sure user/course exist in User/Course table // //User should be enrolled in this course. // //If anyone missing from all thee ..return false // //Otherwise redirect to StaffHome page CourseRolesBOFilters courseRole = new CourseRolesBOFilters(); courseRole.CourseId = courseId; courseRole.UserId = userId; return RedirectToAction("SelectCourse", courseRole, FormMethod.Post); } catch (Exception ex) { string errorMessage = string.Format("Error loading LMS page. Please try again or contact support."); Trace.WriteLine(errorMessage); Trace.WriteLine(ex.ToString()); ModelState.AddModelError("", String.Format("System failed to load LMS page. {0}", ex.Message)); return View(); } } I am getting an error at line return RedirectToAction("SelectCourse", courseRole, FormMethod.Post); The error is: Argument 2: cannot convert from 'BrightScribeDAL.NonDBBO.CourseRolesBOFilters' to 'string'screenshot Can anyone please help
Please take a look at Microsoft documentation about RedirectToAction found here: https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.118).aspx You are sending three parameters to the function, and by looking at the documentation, the only two signatures that has 3 parameters are: RedirectToAction(String, String, Object) RedirectToAction(String, String, RouteValueDictionary) Both requires second parameter to be string, hence your error shown in the image you posted Cannot convert from 'xyz' to 'string' Make sure to send the correct parameters, and you'll be okay.
Hi I hope the below table itself will solve all your problem and doubts. For your current problem , fifth row in table will be helpful that is, RedirectToAction(string actionName,string controllerName,object routeValue) Your Ex: return RedirectToAction("SelectCourse", "AnycontrollerName", new{CourseID = courseId,...(you can pass anyno of route values) }); Useful Link:http://www.dotnetfunda.com/articles/show/3116/to-understand-various-types-of-redirecttoaction-override-methods-in-as Hope above information was helpful Thanks Karthik
How to get the TFS workitem validation error message by code?
I already know WorkItem.Validate method can get an ArrayList of fields in this work item that are not valid(msdn). But they do seem to contain only invalid fields and thus names, but not contain any error messages, i.e. why they're invalid, which is useful for situation of submitting workitem without using the built in TFS controls. How to get error tip like "new bug 1: TF200012: field 'Title' cannot be empty."? For better understanding, please see the picture. I am using VS2010 SP1 Chinese language, and the error discription is translated as above.
Visual Studio is just another client that wraps TFS error messages. You can't capture the TF* errors but you can get the FieldStatus and print you own message. var invalidFields = workItem.Validate(); if (invalidFields.Count > 0) { foreach (Field field in invalidFields) { string errorMessage = string.Empty; if (field.Status == FieldStatus.InvalidEmpty) { errorMessage = string.Format("{0} {1} {2}: TF20012: field \"{3}\" cannot be empty." , field.WorkItem.State , field.WorkItem.Type.Name , field.WorkItem.TemporaryId , field.Name); } //... more handling here Console.WriteLine(errorMessage); } } else // Validation passed { workItem.Save(); }
field.Status.ToString() Worked for me, this will capture the error message.
Peculiar error while displaying error message in a MVC view
I am trying to display error message in a View based on ViewBag status. But the thing is whenever i put a full stop(.) in the error message, error message before (.) is not displayed. It goes like this: #if (#ViewBag.ProfileStatus == 0) { #Html.Label("Error generating Report. Please try again ! ", new { id = "lblStatus" }) } Output: Please try again ! Again if message is: #if (#ViewBag.ProfileStatus == 0) { #Html.Label("Error generating Report..!! ", new { id = "lblStatus" }) } Output: !! Please, can anyone explain why this is happening?
Please use the secondary overload, this will solve your issue: #Html.Label("", String.Format("{0}. Please try again !","Error generating Report")) More info at the following thread
MVC reCapcha Only Returns False
I am using: http://mvcrecaptcha.codeplex.com/ My problem is very simple! bool captchaValid always returns false, no matter what I do. Here is my code: [CaptchaValidator] [HttpPost] public ActionResult ViewWidget(int id, TagwallViewModel model, bool captchaValid) { model.TagwallCollection = new TagWallCollection() { Id = id }; if (!captchaValid) { ModelState.AddModelError("_FORM", "You did not type the verification word correctly. Please try again."); } else It shows no errors.. Things i have done differently, but i think have no influence: The cs files downloaded from codeplex is not in the same folders. I registered on https://www.google.com/recaptcha/admin/create to get my two keys with a online domain, but i'm testing it on localhost. That was my problem, sorry for troubleing you! Having a bad code day. I am using Razor.