RedirettoAction() doesn't takes object - c#

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

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.

Error CS0103 when a variable is actually in the right scope

I have this control (db is the Entity Framework context):
if (db.Sites.Any(s => s.Name.Equals(name))) throw new NameAlreadyInUseException(name);
When I run my tests and debug it fails giving me the error:
Error CS0103: the name 's' does not exist in the current context.
I honestly can't get my head around it and Google hasn't really been helping... any help is appreciated, thanks in advance. Isn't s used correctly here? (I'm still learning, so maybe I missed something but my code here looks ok to me)
Edit:
the debugger triggers the error on this line and I am not using s in any other place other than inside that if statement. (I edited the line to show what happens with the if)
Edit2: complete code of the function
public void CreateSiteOnDb(string connectionString, string name, int timezone, int sessionExpirationTimeInSeconds,
double minimumBidIncrement)
{
CheckInput_CreateSiteOnDb(connectionString, name, timezone, sessionExpirationTimeInSeconds, minimumBidIncrement);
try
{
using (var db = new AuctionSiteContext(connectionString))
{
if (db.Sites.Any(s => s.Name.Equals(name))) throw new NameAlreadyInUseException(name);
var site = new Entities.Site
{
Name = name,
Timezone = timezone,
MinimumIncrement = minimumBidIncrement,
SessionExpirationInSeconds = sessionExpirationTimeInSeconds
};
db.Sites.Add(site);
db.SaveChanges();
}
}
catch(NameAlreadyInUseException)
{
throw;
}
catch(Exception)
{
throw new UnavailableDbException();
}
}
Edit3: Error as shown during debugging
It is not in the right scope.
In the screenshot you are in the scope of CreateSiteOnDb -> try -> using, but s does not belong to that context.
In very basic terms s => .... is converted to function of a class, and it is called from inside Any. so let's assume that our expression is function named Steve. Steve would look like this:
bool Steve(ISite s)
{
return s.Name.Equals(name);
}
this means s is the parameter of Steve, and is only valid inside Steve, which becomes CreateSiteOnDb -> try -> using -> Any -> Steve
So to see s you need to be in two more levels. Please, put your cursor inside the expression and then put a breakpoint.

Modelstate errors not shown correctly

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

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.

How can i use response.redirect from inside a function defined in Class file in c# 3.0

I have a simple function GetPageName(String PageFileName, String LangCode) defined inside a class file. I call this function from default.aspx.cs file, In this function I am not able to use Response.Redirect("Error.aspx") to show user that error has been generated.
Below is example of Code
public static string GetPageName(String PageFileName, String LangCode)
{
String sLangCode = Request("Language");
String pgName = null;
if ( sLangCode.Length > 6)
{
Reponse.Redirect("Error.aspx?msg=Invalid Input");
}
else
{
try
{
String strSql = "SELECT* FROM Table";
Dataset ds = Dataprovider.Connect_SQL(strSql);
}
catch( Exception ex)
{
response.redirect("Error.aspx?msg="+ex.Message);
}
}
return pgName;
}
I have may function defined in Business and Datalayer where i want to trap the error and redirect user to the Error page.
HttpContext.Current.Response.Redirect("error.aspx");
to use it your assembly should reference System.Web.
For a start, in one place you're trying to use:
response.redirect(...);
which wouldn't work anyway - C# is case-sensitive.
But the bigger problem is that normally Response.Redirect uses the Page.Response property to get at the relevant HttpResponse. That isn't available when you're not in a page, of course.
Options:
Use HttpContext.Current.Response to get at the response for the current response for the executing thread
Pass it into the method as a parameter:
// Note: parameter names changed to follow .NET conventions
public static string GetPageName(String pageFileName, String langCode,
HttpResponse response)
{
...
response.Redirect(...);
}
(EDIT: As noted in comments, you also have a SQL Injection vulnerability. Please use parameterized SQL. Likewise showing exception messages directly to users can be a security vulnerability in itself...)

Categories

Resources