getting actionlist to send current url to actionresult - asp.net-mvc

I'm trying to pass my current url to my actionresult but returnUrl always comes up null
#Html.ActionLink("Create Student", "Create", "StudentCenter", new{ returnUrl = Request.RawUrl}, new { #class = "button" })
here's the controller
public ActionResult Create(string returnUrl)
{
HttpCookie cookie = new HttpCookie("redirectCookie",returnUrl);
ViewBag.Sex = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Sex)));
return View();
}

I think you have to use like this
#Html.ActionLink("Create Student", "Create", "StudentCenter", new{ returnUrl = Request.RawUrl.ToString()}, new { #class = "button" })
Please try and send me a feed back
Is your expected string like this "studentCenter/create"?

Related

Contact us form action not found

Not sure why this isn't working, but I suspect it's something to do with routing... (Using MVC5)
When clicking on the submit button I get the following message:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /contact
Using a model as follows:
public class EmailMessageModel
{
/// <summary>Gets or sets from name.</summary>
/// <value>From name.</value>
[Required, Display(Name = "Name")]
public string FromName { get; set; }
}
The view is then as follows:
#model EmailMessageModel
#using (Html.BeginForm("index", "contact", FormMethod.Post, new { enctype = "multipart/form-data", #class = "contact-form" }))
{
#Html.AntiForgeryToken()
#Html.LabelFor(m => m.FromName, new { #class = "control-label" })
#Html.TextBoxFor(m => m.FromName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FromName)
<input type="submit" value="Send Message" id="btnSubmitQuery" />
}
Controller is as follows:
(the breakpoint on the HttpPost Index action is never hit, any ideas why?)
namespace ExternalSite.Controllers
{
using ExternalSite.Models;
using System.Net.Mail;
using System.Web.Mvc;
[RoutePrefix("contact")]
public class ContactController : Controller
{
[HttpGet]
[Route]
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailMessageModel model)
{
// !!!!!!!!!!BREAKPOINT HERE IS NEVER BEING HIT!!!!!!!!!!!
if (ModelState.IsValid)
{
}
return View(model);
}
}
The solution was to add the blank route attribute [Route] to the HttpPost Index method, i.e.
[HttpPost]
[Route]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Index(EmailMessageModel model)
{
// !!!!!!!!!!BREAKPOINT HERE IS NEVER BEING HIT!!!!!!!!!!!
if (ModelState.IsValid)
{
}
return View(model);
}

Register _LoginPartial if(Request.IsAuthenticated)

I'm hitting a dead end with this one. I'm new to MVC and I see similiar issue appearing on SO, but it does not help. I'm basically trying to set a Register action, and once user is registered _LoginPartial view should indicate that the user is authenticated. From various posts and articles I read I believe I'm missing the element of storing this user to the cookie, but I do not know how to achieve this. I will appreciate any hints.
Controler:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
int userId = WebSecurity.GetUserId(model.UserName);
string roleName = ConfigurationManager.AppSettings["CustomerRole"];
if (!Roles.RoleExists(roleName)){ Roles.CreateRole(roleName); }
Roles.AddUserToRole(model.UserName, roleName);
var customer = new Customer();
customer.UserId = userId;
customer.Name = model.Name;
customer.PrivateEmail = model.PrivateEmail;
_customerRepo.Add(customer);
_customerRepo.SaveChanges(); // Customer, Membership, UserProfile added to db, no problems
TempData["Message"] = "User was registered"; // shows
return RedirectToAction("Index", "Home"); // shows
It seems everything is being saved correctly but the partial view does not see this user anymore...
_LoginPartial view
#if(Request.IsAuthenticated) {
<text> user: #Html.ActionLink(User.Identity.Name, "Manage", "Account",routeValues: null, htmlAttributes: new { #class = "username", title = "Change Password" })
#using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
{#Html.AntiForgeryToken()
Log off}
</text>
} else {
<ul>
<li>#Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>#Html.ActionLink("Register", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
You need to call Login() after the SaveChanges();
It should be something like
WebSecurity.Login(model.UserName, model.Password, false);
More information http://www.codeguru.com/csharp/.net/net_asp/mvc/using-simplemembership-in-asp.net-mvc-4.htm

ASP.NET MVC Get id parameter to controller

I use in view
using (Html.BeginForm("Test", "AcceptStatement", "Account", FormMethod.Post, new { id = Model.StatementID }))
in controller:
public ActionResult AcceptStatement(int id)
but id parameter in controller ends up being a null value. How can I get the id parameter value into my controller with Html.BeginForm?
You're using the wrong overload of BeginForm. You are currently passing the following:
actionName: "Test"
controllerName: "AcceptStatement"
routeValues: "Account"
formMethod: FormMethod.Post
htmlAttributes: { id = Model.StatementID }
This is obviously wrong as it makes no sense. You probably wanted:
Html.BeginForm("AcceptStatement", "Account", new { id = Model.StatementID }, FormMethod.Post, null)
Using this overload.
Use the information in this:
Basically, your view:
#using (Html.BeginForm()){
<p> Title: #Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" /></p>
}
</p>
With a Controller of:
public ActionResult Index(string searchString)
{
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);
}
An alternative to passing the model's value to controller method would be to use:
#Html.ActionLink("Details", "Details", new { id=item.BayID })
With your controller method being something like:
public ActionResult Details(int? id)
{
...

Redirect after log-in cannot work

I have a form to manage the insertion of comments:
#model GatorsWebSite.Comment
#using (Html.BeginForm("Create", "Comments", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.ArticleID)
#Html.TextAreaFor(m => m.Text, new { #class = "form-control wide", #placeholder = "Type your comment", #rows = "3" })
#Html.ValidationMessageFor(m => m.Text, "", new { #class = "text-danger" })
}
This is the action on controller:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Text, ArticleID")] Comment comment){
if (comment == null || comment.ArticleID <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid){
comment.Date = DateTime.Now;
comment.UserID = User.Identity.GetUserId();
_commentRepository.Add(comment);
_commentRepository.Save();
}
return RedirectToAction("Details", "News", new { ID = comment.ArticleID });
}
Since the action is under authorization, if the user is not logged in
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl){
if (ModelState.IsValid){
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null){
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
the redirect url will be Comments/Create and will fail with a 404 error, does exist a general solution to manage this problem, since I cannot use a simple redirect to action?
One alternative is to make a Create get action and make it redirect to articles/news list page. For Example:
public ActionResult Create(){
return RedirectToAction("Index", "News");
}
EDIT
and is exactly what I've done:
[Authorize]
[HttpGet]
public ActionResult Create([Bind(Include = "Text, ArticleID")] Comment comment)
{
if (comment == null || comment.ArticleID <= 0)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
comment.Date = DateTime.Now;
comment.UserID = User.Identity.GetUserId();
_commentRepository.Add(comment);
_commentRepository.Save();
}
return RedirectToAction("Details", "News", new { ID = comment.ArticleID });
}
...and work like a charm

ReturnUrl QueryString always is null in MVC 4

i have a action method for login with get method:
public virtual ActionResult LogIn()
{
return View();
}
and an action method for Post method which post in Ajax call with Ajax.BeginForm(),like:
[HttpPost]
[AjaxOnly]
[ValidateAntiForgeryToken]
public virtual ActionResult LogIn(LogInViewModel loginInfo, string returnUrl)
{
...
}
But returnUrl always is null!!!
i use MVC 4.
what is cause of this problem?
You have to send the returnUrl back to the server. For example your login form should take returnUrl as a parameter:
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
....
<input type="submit" value="Log in" />
}
which was previously saved at the server side in your login action, invoked as a result of usage AuthorizeAttribute with ReturnUrl passed in the query string:
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
Not sure what your view looks like, but if you have something like:
#using (Html.BeginForm())
{
}
...then returnUrl should have a populated value, that's if it came from another url.
In my scenario it was always null, and I am assuming it was probably the same way that you did it. I had it like this:
#using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { role = "form" }))
{
}
All that I did was change it to look like this:
#using (Html.BeginForm("LogOn", "Account", new { returnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post, new { role = "form" }))
{
}
returnUrl now has a value that I can work with.
in continue for Completion good answer of #Jaroslaw Waliszko,cause of this problem is:
because we use a ajax request for submit form,unobtrusive ajax use
$("form").serialize();
for this form and at this case(use ajax) ReturnUrl(and any other parameter) not send to server and only form input element send to server,So MVC Auto ModelBinding not bind ReturnUrl and we must use #Jaroslaw Waliszko solution at this state.
serialize
Encode a set of form elements as a string for submission.

Resources