MVC controller's parameter always null - c#

i can't figure out why the username in the controller always returned as null. When i clicked the button, the button works fine and return the member's username.
http://localhost:50555/Account/UserDetails/member1
In my view
<button data-get="/Account/UserDetails/#m.Username">Details</button>
In controller
[Authorize(Roles = "Supervisor, Admin")]
public ActionResult UserDetails(string username)
{
var model = db.Members.Find(username);
if (model == null)
{
return RedirectToAction("ManageUsers");
}
return View(model);
}

You are not taking the value of username from the querystring. You are expecting a route parameter. So you will have to specify the route parameter as shown below:
[Authorize(Roles = "Supervisor, Admin")]
[HttpGet("{username}")]
public ActionResult UserDetails(string username)
{
var model = db.Members.Find(username);
if (model == null)
{
return RedirectToAction("ManageUsers");
}
return View(model);
}
Refer this documentation for more details.

Related

GET Method is going to the right page but stills runs through POST method and has the POST in the URL

I have a POST method that returns me to my summary page that looks like this
public ActionResult SpecialOrderSelection(ItemViewModel model)
{
if (ModelState.IsValid)
{
JobOrder jobOrder = db.JobOrders.Find(model.Id);
if (jobOrder == null)
{
return HttpNotFound();
}
ViewBag.JobOrderID = jobOrder.ID;
}
return SpecialOrderSummary(model);
}
And here is my Summary GET method
public ActionResult SpecialOrderSummary(ItemViewModel model)
{
return View("SpecialOrderSummary", model);
}
It sends me to my SpecialOrderSummary View Page, however the URL still displays as what my POST method is and not my GET. Also on every refresh it goes to the post first.
Why is this?
This is normal, because mvc runs like this.
You should use redirect,
public ActionResult SpecialOrderSelection(ItemViewModel model)
{
if (ModelState.IsValid)
{
JobOrder jobOrder = db.JobOrders.Find(model.Id);
if (jobOrder == null)
{
return HttpNotFound();
}
ViewBag.JobOrderID = jobOrder.ID;
}
return Redirect("SpecialOrderSummary?(your model serialize)");;
}

Sending a message from one controller to another

When I register a user, it redirects to the Manage controller (where the user profile is).
return RedirectToAction("Index", "Manage", new { id = user.Id });
and in the Manage Controller
[Route("")]
[Route("{id}")]
public ActionResult Index(string id)
{
if (id == null)
{
id = User.Identity.GetUserId();
}
var user = UserManager.FindById(id);
return View(user);
}
I need to send a string message of "newUser", so I can display a modal message the first time the user makes the account and is redirected to their profile.
My question is how exactly? I tried to send a string parameter like this:
return RedirectToAction("Index", "Manage", new { id = user.Id, msg = "newUser" });
and change the Index constructor to Index(string id, string msg) but for some reason both the id and msg get the value of the user id.
Anyone know a solution to this?
Manage / Index
public ActionResult Index(string id)
{
if (id == null)
{
id = User.Identity.GetUserId();
}
var user = UserManager.FindById(id);
return View(user);
}
You can make use of TempData for passing data from one controller to anhother.
Example :
public ActionResult Index()
{
var model = new Review()
{
Body = "Start",
Rating=5
};
TempData["ModelName"] = model;
return RedirectToAction("About");
}
public ActionResult About()
{
var model= TempData["ModelName"];
return View(model);
}
Refer this link for more info : https://www.codeproject.com/articles/476967/what-is-viewdata-viewbag-and-tempdata-mvc-option
You code syntax is almost correct except you are missing " in msg = "newUser
You could have use TempData for sending data from controller to controller.
For more reference :
http://www.tutorialsteacher.com/mvc/tempdata-in-asp.net-mvc

Calling View present in HomeController from Action Method of otherController

Can anyone please help me? I am trying to call a view which is present in Home Controller directly from the action method of another controller. I don't want to use the return redirectToAction() method, but rather would like to call the view of HomeController directly. In HomeController I have this HttpGet Method:
public ActionResult SuperAdmin()
{
if (Session["User"] != null)
{
TempData["BindGrid"] = objDBContext.tbl_Student.Where(X => X.RegistrationConfirmed == false).ToList();
return View(); //Go to SuperAdmin View if condition is true
}
else
{
return View("Login", "Home"); //else redirect to Login view
}
}
Present Controller from where i would like to call HomeController SuperAdmin View
public ActionResult Search(string Search)
{
if (Session["User"] != null)
{
if (Search != string.Empty)
{
TempData["BindGrid"] = objDBContext.tbl_Student.Where(X => (X.UserName.StartsWith(Search) || Search == null) && (X.RegistrationConfirmed == false));
}
return View("SuperAdmin", "Home"); //If true, go to SuperAdmin view directly
}
else
{
return RedirectToAction("Login", "Home");
}
}
You can directly return a different view like:
return View("yourViewName", Model); //if it is in same controller and if you pass model then pass model in this way
if your view is in different controller then
return View("FolderName/ViewName", Model ); // pass a view of a different controller with model. Just specify view name and it's folder name

Is There any way to know that a request is a made using Redirect() method in ASP.NET MVC

Here i want to check the request type,
If request is coming from Redirect() method in my applicaton
Add some message to ViewBag to show on Login page
Else don't add message (where user opens login page directly)
public ActionResult Login()
{
//if(RequestIsARedirect)
//ViewBag.LoginMessage = "Please login to Continue";
return View();
}
Thanks in advance.
Wouldn't it be easier if you'll redirect with a parameter?
return RedirectToAction("Login", "Account", new { returnUrl = this.Request.Url });
Or
return Redirect("/Account/Login?returnUrl=' + this.Request.Url });
Then check that returnUrl parameter:
public ActionResult Login(string returnUrl)
{
if (!String.IsNullOrEmpty(returnUrl))
ViewBag.Message = "Please login to continue";
}
Also, if you'll use the built-it [Authorize] action-filter, it will automatically add the returnUrl as parameter to the login Url when redirecting.
See MSDN
The way to do it without adding extra url params is using TempData, which is The data stored ... for only one request..
http://msdn.microsoft.com/en-us/library/system.web.mvc.viewpage.tempdata(v=vs.118).aspx
The code would be like this then:
public ActionResult EntryPoint()
{
TempData["CameFromEntryPoint"] = true;
return Redirect("Login");
}
public ActionResult Login()
{
if(RequestIsARedirect())
ViewBag.LoginMessage = "Please login to Continue";
return View();
}
private bool RequestIsARedirect()
{
return TempData["CameFromEntryPoint"] != null && (bool) TempData["CameFromEntryPoint"];
}

MVC how to return a view after an IF statement

My page has a search box which for has a few radio buttons. Depending on which radio button is selected will depend on which view is shown.
However, I don't know how to return the View.
My code is
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
CandidateResults();
else
JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
But this displays nothing on screen (a white page). This makes sense but I don't want to return Index, I want to return a new page (called either JobResults or Candidates) and create a View for both of these new pages but when I right click in my methods (JobResults() or Candidates()) I don't get the option to Add View.
At this stage I'm lost, can any one please give advice.
Either return the view from Index or redirect to CandidateResults or JobResults actions.
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return CandidateResults();
else
return JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
Try this
public ActionResult Index(string jobType)
{
return (jobType.ToLower() == "this") ?
RedirectToAction("CandidateResults") :
RedirectToAction("JobResults");
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}
In your private methods you have to specify the actual view you want to display.
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
CandidateResults();
else
JobResults();
}
private ActionResult CandidateResults()
{
var model = //logic
return View("CandidateResults", model);
}
private ActionResult JobResults()
{
var model = //logic
return View("JobResults", model);
}
This happens because of the way the view engine works. The action name for the current request is always Index when the index function is called. Even if you call another method, the view engine will use the name of the current action and not the name of the currently executing function.
Just you need to redirect the user to proper controller method and that method will return its View as below:
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return RedirectToAction("CandidateResults","ControllerName");
else
return RedirectToAction("JobResults","ControllerName");
}
public ActionResult Index(string jobType)
{
if (jobType.ToLower() == "this")
return RedirectToAction("CandidateResults");
return RedirectToAction("JobResults");
}
private ActionResult CandidateResults()
{
var model = //logic
return View(model);
}
private ActionResult JobResults()
{
var model = //logic
return View(model);
}

Categories

Resources