I have a Login View Page with 2 partial views _LoginPartial and _RegisterPartial. And in _RegisterPartial I have dropdownlist that contains the roles.
#Html.DropDownListFor(m => m.CompanyProfile, new SelectList(ViewBag.CompanyProfiles, "AccountId", "AccountName"), "Select", new { #class = "form-control" })
I'm initializing this dropdownlist in the GET Method as
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
ViewBag.ReturnUrl = returnUrl;
return View();
}
and my code for getting the list from database is
public List<abo_AccountType> GetCompanyProfiles()
{
List<abo_AccountType> companyProfiles = new List<abo_AccountType>();
companyProfiles = db.GetAccountTypes().ToList();
return companyProfiles;
}
The list is initialized when we open the Login Page and I know that I need to initialize the dropdownlist again in the POST method, so I'm doing that just like I did it in the GET Method
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
if (ModelState.IsValid)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
string[] errors = util.CheckDuplicateAccount(model);
if (errors == null)
{
long currentUser = Convert.ToInt64(System.Web.HttpContext.Current.User.Identity.GetUserId());
util.CreateNewAccount(model, currentUser);
}
else
{
AddErrors(errors);
}
}
return RedirectToAction("Login");
}
Even though I'm initializing the dropdown again I still get the error that Value cannot be null. Parameter name: items.
I've searched almost all the answers on SO and they all say that I need to initialize the dropdown again, which I'm doing, so why am I still getting this error.
You should generate "GET" method for Register and set CompanyProfiles in there.
[HttpGet]
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View();
}
Create another model that having both the properties of that two models and pass it in your post action.
[HttpGet]
[AllowAnonymous]
public ActionResult Register(combinedModel model)
{
ViewBag.CompanyProfiles = util.GetCompanyProfiles();
return View(model);
}
Related
So I have a controller and I can seem to understand how to pass a parameter to my ActionResult method.
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{name}/{id}",
defaults: new { controller = "Project", name = "Search", id = UrlParameter.Optional }
);
This is my route. Now in my controller i've created a method
[HttpGet]
public ActionResult Search()
{
return View();
}
[HttpPost]
public ActionResult Search(int Id)
{
ViewBag.iD = Id;
return View();
}
And in my view
<body>
<div>
ASDF + #ViewBag.iD
</div>
</body>
How can I pass a value to my iD parameter from Search Action? It seems whatever I call
http://localhost:52992/Project/Search/id=2
or http://localhost:52992/Project/Search/1
Both method go into the Search() method, none goes to Search(int iD).
What Am I missing?
A link in your view (or a form with FormMethod.Get or entering a url in the address bar) makes a GET call, not a POST, so your method should be
[HttpGet]
public ActionResult Search(int ID)
{
// do something based on the value of ID
ViewBag.iD = ID;
return View();
}
and delete the [HttpPost] method.
You have to pass value from the HttpGet 'SearchAction' method. if you pass from it, then only the value will be shown in the view
[HttpGet]
public ActionResult Search()
{
ViewBag.iD = your Id value here;
return View();
}
on intial load the get method will be called, on submission only the 'post' method will be call.
hope this helps.
On your view
<a href='#Url.Action("ActionName", "ControllerName", new { id= 10})'>...</a>
OR
#{
int id = 10
}
...
On Your Action
Public ActionResult Search(int id)
{
Viewbag.Id = id;
return view();
}
Action is by default on [HTTPGET] you wont have to mention it
I have a return url send after a user logs in:
e.g.
/Account/SignIn?ReturnUrl=%2fToDoItems%2fCreate
However, the value in the controller isn't binding.
[HttpPost]
[ActionName("SignIn")]
public ActionResult SignInConfirmation(UserCredentialsModel model, string returnUrl)
{
if (ModelState.IsValid)
Also, the Request.QueryString is empty (bar the Length).
How do I bind the query string params to the controller?
As per below, I've tried capitalising the parameter name:
public ActionResult SignInConfirmation(UserCredentialsModel model, [Bind(Include = "ReturnUrl")] string ReturnUrl)
You want to retrieve ReturnUrl from HttpGet method, and send it back on postback.
View
#using (Html.BeginForm("SignInConfirmation", "YOUR_CONTROLLER",
new { ReturnUrl = ViewBag.ReturnUrl },
FormMethod.Post, new { role = "form" }))
{
....
}
Controller
public ActionResult SignInConfirmation(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
[HttpPost]
public ActionResult SignInConfirmation(UserCredentialsModel model, string returnUrl)
{
}
I'm using MVC4 and I have 2 methods in my controller:
Get Method
public ActionResult Create()
{
var vm = new User
{
Client= new Catastro_Cliente()
Genre = ClienteRepository.GetGenres(),
Type= ClienteRepository.GetTypes()
};
ViewBag.Genre = new SelectList(vm.Genre, "IdGenre", "Genre");
ViewBag.Type= new SelectList(vm.Type, "IdType", "Type");
return View(vm);
}
Post Method
[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
if(Validator(client.document))
{
ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
}
if(ModelState.IsValid)
{
return View();
}
}
Basically, I'm trying keep all the data that the user filled in before the post Method,
I tried with return RedirectToAction("Create"); but it always refreshes the page.
You have to pass back the posted model when you call View. What you need is something like:
[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
if(Validator(client.document))
{
ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
}
if(ModelState.IsValid)
{
// save to database of whatever
// this is a successful response
return RedirectToAction("Index");
}
// There's some error so return view with posted data:
return View(client);
}
Noob needs help!) How can I return an existing view from a new action within the same controller?
For example I have a following code:
[HttpGet]
public ActionResult Index()
{
return View(); //returns Index.cshtml
}
[HttpPost]
public ActionResult Index(string id, string condition)
{
SomeModel.ID = id;
SomeModel.Condition = condition;
return View(SomeModel); //returns Index.cshtml delegating the model
}
public ActionResult someAction()
{
return View(); //How to make this action return Index.cshtml??
}
You can specify the view name to return:
public ActionResult someAction()
{
return View("Index");
}
public ActionResult someAction()
{
return View("Index"); //How to make this action return Index.cshtml??
}
Just add
return View("YourView");
If you want send a model to it you can do this
var model = new YourViewModel
{
}
return View("YourView", model);
I'm having trouble when handling the Post request for my controller:
[HttpGet]
public ActionResult Crear()
{
CarreraRepository carreraRepository = new CarreraRepository();
var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
var carrerasList = new SelectList(carreras, "ID", "Nombre");
ViewData["Carreras"] = carrerasList;
Materia materia = new Materia();
return View(materia);
}
[HttpPost]
public ActionResult Crear(Materia materia, FormCollection values)
{
if (ModelState.IsValid)
{
repo.Add(materia);
repo.Save();
return RedirectToAction("Index");
}
return View(materia);
}
When the HttpGet action runs, the form to create renders fine. The values are set correctly on the DropDownList and everything is peachy; when I try to submit the form (run the HttpPost action) I receive the error.
Can anyone help me out?
Is it because the HttpPost doesn't have a ViewData declared? Thanks for the help.
Since you are Posting on the same View, when you post to Creat the ViewData["Carreras"] is not created. You have to load the data of your carreras again in your Post.
[HttpPost]
public ActionResult Crear(Materia materia, FormCollection values)
{
CarreraRepository carreraRepository = new CarreraRepository();
var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
var carrerasList = new SelectList(carreras, "ID", "Nombre");
ViewData["Carreras"] = carrerasList;
if (ModelState.IsValid)
{
repo.Add(materia);
repo.Save();
return RedirectToAction("Index");
}
return View(materia);
}