How to pass a value from a controller method to an another? - c#

I'm beginner in MVC3, and I want to get a value from an another controller's method. Here the two methods:
[HttpPost]
public ActionResult Create(TennisClub tennisclub)
{
if (ModelState.IsValid)
{
db.TennisClubs.Add(tennisclub);
db.SaveChanges();
return RedirectToAction("AssignManager");
}
return View(tennisclub);
}
[HttpPost]
public ActionResult AssignManager(Manager manager)
{
}
So, when I'm creating a new tennis club, Immediately I would like to assign a manager to it... For that I need the primary key "ID".
So my question is: How to get this ID in my "AssignManager" method ? Thanks in advance

You cannot redirect to an action decorated with the [HttpPost] attribute. That's not how a redirect works. A redirect means that you are sending a 301 HTTP status code to the client with the new Location header and the client issues a GET request to this new location.
So once you remove the [HttpPost] attribute from your AssignManager action you could pass the id as parameter:
return RedirectToAction("AssignManager", new { id = "123" });
and then:
[HttpPost]
public ActionResult AssignManager(int id)
{
}

Basically, you need to have a GET AssignManager method, too, which would have a parameter telling it to which TennisClub the manager should be assigned:
[HttpGet]
public ActionResult AssignManager(int tennisClubId)
{
// here, you will want to return AssignManager view
}
And when redirecting to AssignManager from Create, you can specify the id of TennisClub:
return RedirectToAction("AssignManager", new { tennisClubId = tennisclub.Id });

return RedirectToAction("AssignManager", new { id = tennisclub.Id });
Also you need to remove the [HttpPost] attribute from your action
public ActionResult AssignManager(int id) {
//...
}

Related

call another actionresult from controller with multiple parameters netcore mvc

I have a method (MethodA) in my controller that needs to return another ActionResult (methodB) in that same controller, with some parameters as payload. For this I use a RedirectToAction(nameof(methodB), new { param1=param1, param2=param2 } ) at the end of MethodA.
When I debug, all the parameters are loaded and contain the expected values. However when it arrives at methodB, the two parameters are empty.
MethodA
[HttpPost]
public ActionResult Bulkimport(int id)
{
int customerId = 5;
ReturnModel returnMessage = new ReturnModel();
returnMessage.Message= "All data loaded";
returnMessage.returnModel = returnModel; //contains list with some data
return RedirectToAction(nameof(Bulkimport), new { id = customerId, model = returnMessage });
}
MethodB
[HttpGet]
public ActionResult Bulkimport(int id, MessageModel model)
{
// Do stuff, but MessageModel and id are null.
return View();
}
Does anyone have an idea what might be happening here?
Additional: I have some experiences that additional parameters are presented in the receiving view as a querystring in the url in the browser. Is there any way to prevent it?
Thanks
Change:
return RedirectToAction(nameof(Bulkimport), new { id = customerId, model = returnMessage });
To
return Bulkimport( customerId, returnMessage);
````

Entity Framework : send list between methods in the same controller not working

I want to send a list to this method (inside the same controller)
[HttpGet]
public ActionResult listaExpedientesPOrCriterio(List<Expediente> expedientes)
{
ExpedienteListPorCriterio vm = new ExpedienteListPorCriterio(expedientes);
//List<Expediente> expedientes = db.Expediente.ToList();
//SelectList Tramitees = new SelectList(expedientes, "Codigo", "FechaCreacion");
return View(vm);
}
Im using this inside the other method, to send the list
return RedirectToAction("listaExpedientesPOrCriterio", "expedientes");
but I receive only null. Any idea whats going on?
You have [HttpGet] action attribute. How you intend to send to it List<T> at all? Instead, you have to use [HttpPost] and pass data in request's body, but at this case you won't can to RedirectToAction. But you can pass your expedientes list from one action to another via TempData also preserving [HttpGet]:
[HttpGet]
public ActionResult AnotherActionName()
{
//some code...
TempData["expedientes"] = expedientes;
return RedirectToAction("listaExpedientesPOrCriterio"/*, "expedientes"*/);
}
[HttpGet]
public ActionResult listaExpedientesPOrCriterio(/*List<Expediente> expedientes*/)
{
var expedientes = (List<Expediente>)TempData["expedientes"];
var vm = new ExpedienteListPorCriterio(expedientes);
return View(vm);
}

How to call controller method and pass the object from ajax call in ASP.Net MVC

I am in a learning process and working on ASP.net MVC 5 project. So, I have a model view which has other model views in it.
Parent Model View
public class FullConfigMV
{
some properties here
public ElementStyleMV Page { get; set; }
}
Now below is what I want to achieve.
Make an ajax call
once the ajax call hits the controller function set some values
now from there I need to pass that object to another controller action which will return it's view.
Step 1.
<script>
$(document).ready(function()
{
$("#tan").change(function()
{
alert(this.value);
$.ajax({
type: 'POST',
url: '/Settings/GetAvailableLocationsFor',
data: { accountId: 28462, groupId: 35},
success: function (data) {
//Whatever
},
error: function () {
DisplayError('Failed to load the data.');
}
});
});
});
</script>
After step 1 my breakpoint hits at
public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
{
FullConfigMV configData = SetLoader.GetDSettings(accountId, groupId);
Utils.SiteCss = configData.CssStyles();
// NOW AT THIS PLACE I WANT TO CALL ANOTHER CONTROLLER FUNCTION
// AND PASS THE `configData Obj`
return View();
}
I know we have something like
return RedirectToAction("Index","Home");
BUT HOW TO PASS THE config Obj
The controller function that I want to call is in
Home Controller and the action name is Index
public ActionResult Index(FullConfigMV data)
{
return View();
}
If the requirement seems weird then kindly bear/humor me on this.
EDIT
After the solution suggested "use TempData " But the problem is I have two index action in my controller. I want the SECOND Index Action to get hit. But the first one is getting hit.
First:
public ActionResult Index()
{
}
Second
[HttpPost]
public ActionResult Index(FullConfigMV data)
{
}
Code used is
public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
{
FullConfigMV configData = SetLoader.GetDSettings(accountId, groupId);
SimUtils.SiteCss = configData.CssStyles();
TempData["config"] = configData;
return RedirectToAction("Index", "Home");
}
You can achieve this using TempData. From https://msdn.microsoft.com/en-us/library/system.web.mvc.tempdatadictionary(v=vs.118).aspx:
"A typical use for a TempDataDictionary object is to pass data from an action method when it redirects to another action method."
There's plenty of documentation out there but simply use
TempData["config"] = configData;
In your first actionresult, and retrieve it in your Home> Index with
var configData = TempData["config"] as FullConfigMV;
I am not 100% on this, but you might be able to pass that as a route.. if not then use TempData.
Example:
public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
{
FullConfigMV configData = SetLoader.GetDSettings(accountId, groupId);
Utils.SiteCss = configData.CssStyles();
return RedirectToAction("Index","Home", new { data = configData});
}
Or if above doesn't work:
public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
{
FullConfigMV configData = SetLoader.GetDSettings(accountId, groupId);
Utils.SiteCss = configData.CssStyles();
TempData["config"] = configData;
return RedirectToAction("Index","Home");
}
// Index ActionResult
public ActionResult Index()
{
if (TempData["config"] != null)
{
FullConfigMV variableName = (FullConfigMV)TempData["config"];
...
return View(/*whatever you want here*/);
}
return View();
}
Let me know if that helps
For your question
After the solution suggested "use TempData " But the problem is I have two index action in my controller. I want the SECOND Index Action to get hit. But the first one is getting hit what you can do is based on some data which you can set in TempData you can call return Index(data) from your first index method, you can get data through Tempdata or some other variable. This will call you second index method through first index method.

RedirectToAction with a parameter not working

i am trying to redirect to another action within the same controller
action is called index
[HttpGet]
public ActionResult Search(string city)
{
return RedirectToAction("Index", "Rentals", new { CityName = city });
}
this is index action
[HttpPost]
public ActionResult Index(String CityName)
{
}
am i missing something?
You are trying to redirect action which is searching for a matching action but in this case there is no get action, so you have to add a get method to accept redirect. If you want, you can check the HTTPGET or POST inside the method
[HttpPost]<---- Remove this
public ActionResult Index(String CityName)
{
}
Please change HttpPost to HttpGet
[HttpGet]
public ActionResult Index(String CityName)
{
}
Because whenever you call the Action, then the GET method will be first called.
As the two actions are in the same controller, you could call the Index method directly from Search like this:
return Index(city);
not necessarily to user the RedirectToAction method.

RedirectToAction isn't working correctly

I have a simple MVC2 app that doesn't seem to Redirect correctly. The code is setup as follows:
[HttpPost]
[Authorize]
public ActionResult QuickAddEvent(CalendarEvent calEvent)
{
if (ModelState.IsValid)
{
int eventID = repo.AddEvent(calEvent);
return RedirectToAction("Event", new { id = eventID });
}
return RedirectToAction("Index", "Home");
}
[ChildActionOnly]
public ActionResult QuickAddEvent()
{
return PartialView();
}
public ActionResult Event(int id)
{
CalendarEvent curEvent = repo.ByID(id);
return View(curEvent);
}
The problem I am running into is that no matter what the ModelState is on HttpPost the page redirects to itself. That is, no matter what the model state is, I always end up at /EventCalendar/Index instead of one of the two specified actions.
Since QuickAddEvent is returning a PartialView, the form action isposting to /EventCalendar/Index and not /EventCalendar/QuickAddEvent. The fix is changing the action name for the [httpPost] to index

Categories

Resources