Why in this C# .NET controller method do I have this signature? - c#

I am pretty new to C# .NET and I have the following doubt.
On a page on which I am working on I found the following link:
<a class="ui-btn-inline ui-btn ui-icon-delete ui-btn-icon-notext ui-corner-all" href="#Url.Action("Delete", "Groups", new { id = item.gruppoId })">Delete</a>
This link call a Delete() method on a GroupsController class.
Ok, this is this method:
public ActionResult Delete(int id = 0)
{
.......................
.......................
.......................
DO SOME STUFF
.......................
.......................
.......................
return View(model);
}
My doubt is related to the signature of this method: why is the parameter int id = 0 ?
What does the = 0 mean? To begin with I thought that this was a simple initialization and that it change the it value to 0 but using the debbugger I discovered that it don't change the id value. So what it exactly do?

It's called an optional parameter. It means you can call the method with no argument, like this:
Delete();
If you do that, the value of the id parameter in the function will be 0.

You're right in saying that the = 0 sets the value of the id parameter.
But it's important to note that it only does so when you do not pass that parameter.
Take for example:
public void SaySomething( var something = "Hello" )
{
Console.WriteLine( something );
}
//...
SaySomething();
SaySomething("I am sleeping.");
The first call to the function does not pass a parameter. Therefore, the default value "Hello" is used to write to the console.
The second call already sets a value for the parameter, so it does not get overwritten by the default value you set up. "I am sleeping." will be printed in this case.

Related

Getting value from one action method to other inside same controller

I have two action methods inside a controller. With the help of first action method, I am fetching the required data from database and I need to get this fetched data inside the second action method. I need to achieve this without passing any parameter to the second method. I don’t know how to do this as I am new to MVC.
Method 1:
public ActionResult GetData(HttpPostedFileBase file)
{
string folderPath = Server.MapPath(ConfigurationManager.AppSettings["BackupPath"]);
List<string> invalidRecords = new List<string>();
string backupFileName = FileUpload.BackupFile(file, folderPath);
invalidRecords = File.GetDataFromDB(backupFileName);
List<DataVM> lst = serviceData.GetAllData();
return View(lst);
}
Method 2:
[HttpPost]
public JsonResult GetInvalidRecords()
{
List<string> InvalidVehicleId = InvalidRecords;
return new JsonResult { Data = InvalidRecords };
}
You can use a session variable to hold the value of your 'lst' variable in your 'GetData' action:
Session["data"] = lst
Then you can retrieve it as follows and cast it to the appropriate type:
var data = (List<DataVM>)Session["data"]
https://msdn.microsoft.com/en-us/library/ms178581.aspx
You can use TempData as well
TempData["Name of Tempdata variable "]= File.GetDataFromDB(backupFileName)
and in other action you can recieve it
var getdatafromanotherAction= TempData["Name of Tempdata variable"]
If you want to call both action methods in single call, You can use
return RedirectToAction("GetInvalidRecords") in the first method. Also, you can create a class level private variable _listdata. Set it in first method , get in second method.
If you want to keep data between the 2 calls, use Tempdata.Keep and Tempdata.Peek but you need to make sure that call for second method immediately follows first method. Tempdata works between 2 requests only unless you extend its duration by using .Keep and .Peek once more.
If these two methods are to be called few calls apart, you can use session variable to keep the data.
Alternatively, you can keep the parameter of the second method call optional. So, it won't hurt other calls of the jsonresult method. Inside the method, you can check whether parameter is empty or not.

Assign values in Action list?

i had a null value error in my test class
[Test]
public void when_send_the_command_it_execute_correct_command_handler()
{
//Arrange
var commandBus = new CommandBus();
ICommand commandforsend=null;
IMetaData metaDataforsend=null;
Action<ICommand, IMetaData> fakeHandler = (fakecommand, fakemetadata) =>
{
commandforsend = fakecommand;
metaDataforsend = fakemetadata;
};
commandforsend and metaDataforsend values are still null
what can happen ? help me thank you !
You are defining an Action but you are never calling it. Your code is equivalent to a separate method that assigns the values but that you don't call so the code inside the method never runs.
If you want to execute the fakeHandler you should add the following line below the declaration:
fakeHandler(aFakeCommand, aFakeMetadata);`
As you can see, this is the same as calling a regular method. You need to supply values for both parameters (fakecommand and fakemetadata).
You can find more info in the MSDN documentation.
Since your code doesn't execute fakeHandler, this behavior is OK, because you've just declared a anonymous method without executing it.

How to call specific Controller method via DropDownList from SpecificView.aspx on Form in MVC.NET?

I need to call specific method ( probably action event ) of DropDownList when some item has been selected. When this will occure, I have to fetch the data from 2 tables. For that, I would require some action to register, This Is almost done, but with empty arguement, I need that when user clicks on List or select some data from it, it should post back the controller method which will be called via arguments of object( tblCourse, int id) like...
Now In the View.aspx , Code is:
<%: Html.DropDownList("ProgramName", ViewData["ProgramID"] as SelectList,new { onchange = #"
var form = document.forms[0];
form.action='OnProgramSelection';
form.submit();"
}) %>
and in Controller:
public bool OnProgramSelection(tblProgram a_Programs)
{
/*
string ProgramName = a_tblProgram.ProgramName;
string instituteName = a_tblProgram.tblInstitute.InstituteName;
*/
return false;
}
I want something, that OnProgramSelection can accept any no of arguments of whatever the type would be.
To define a method that takes a variable number of parameters use the params keyword
The params keyword lets you specify a method parameter that takes a
variable number of arguments.
You can send a comma-separated list of arguments of the type specified
in the parameter declaration, or an array of arguments of the
specified type. You also can send no arguments.
No additional parameters are permitted after the params keyword in a
method declaration, and only one params keyword is permitted in a
method declaration.
From MSDN documentation

How to verify an 'int?' parameter in C# to avoid exceptions in controller page?

I want to create a class which validate different inputs.
In Controller, I have a simple ActionResult method type.
public ActionResult Detail( int? id ) {
ViewData["value"] = _something.GetValueById( id );
return View();
}
If you navigate to http://localhost/Home/Detail/3 then the controller return the View where it shows available values by id (it is integer) from model.
If ID is null then the controller redirect me to all values.
If you change the ID route (like http://localhost/Home/Detail/3fx) to different data type then the controller returns red page. (with exception)
I want to check that ID is int or not to avoid red page error (with list of exceptions).
I saw that isNaN is only for double data type.
Sorry if my question is annoying.
You can add a route constraint to force the ID parameter to be a valid integer.
routes.MapRoute(
"MyRoute",
"Home/Details/{id}",
new {controller="Home", action="Details", id = UrlParameter.Optional},
new {id = #"\d+" }
);
If I understand your example correctly, then you can't check the type of the ID before it gets to your Detail function, correct?
In this case I would change your "int? id" to "object id". Then you can check the type of object in the function itself. Something like...
public ActionResult Detail(object id)
{
int myID;
if (int.TryParse(id.ToString(), out myID))
{
ViewData["value"] = _discipline.GetValueById(id);
return View();
}
}
This might help
string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
MessageBox.Show(Num.ToString());
else
MessageBox.Show("Invalid number");
check this link
http://social.msdn.microsoft.com/forums/en-US/winforms/thread/84990ad2-5046-472b-b103-f862bfcd5dbc/

Question about Out and Return?

In this code (from the WCF REST starterkit - preview2):
protected override SampleItem OnAddItem(SampleItem initialValue, out string id)
{
// TODO: Change the sample implementation here
id = Guid.NewGuid().ToString();
this.items.Add(id, initialValue);
return initialValue;
}
Am I getting back id as String, or the initialValue as SampleItem?
Edit:
Looks like I get both back, so what would a simple example of the method call look like assigned to a couple of variables?
You will get back id in the string that you pass as a parameter to the method. Also, the method will return the SampleItem instance.
SampleItem myItem = new SampleItem();
string newId = string.Empty;
myItem = OnAddItem(myItem, out newId);
// now myItem will be assigned with SampleItem returned from the
// OnAddItem method, and newId will be updated with the id assigned
// within that method
You're getting both.
You are getting back both.
You will pass in a string variable for ID and that will be returned to you via the 'out' modifier. The function will also return the SampleItem instance initialValue that you passed in.
You are getting back both. An out parameter is just an additional way to to return a value offered by some programming languages.

Categories

Resources