I can´t get into the HttpPost part of the controller.
I´ve created another controller and the problem is the same
I was working fine before
I´ve added tags [Route("CrearSolicitud")]
[HttpPost, ActionName("CrearSolicitud")]
I´ve haven´t added anything to the routing part
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
It goes to http://localhost:55935/Solicitudes
instead of http://localhost:55935/Solicitudes/CrearSolicitud
public class SolicitudesController : Controller
{
ApplicationDbContext db = new ApplicationDbContext();
// GET: Solicitudes
public ActionResult Index()
{
return View();
}
//Get
public ActionResult Solicitud()
{
return View();
}
//Post
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Solicitud(Solicitudes s)
{
s.Id = "e17cba68-0a0b-4d6e-abaf-8026cb91fcd1";
s.fk_tipo_transaccion = 3;
s.fk_estado_solicitud = 1;
db.Solicitudes.Add(s);
db.SaveChanges();
return View();
}
The view
#model HGRecursosHumanos4.Models.Solicitudes
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (#Html.BeginForm("CrearSolicitud", "Solicitudes", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="container">
<div class="form-group col-md-5">
#Html.LabelFor(model => model.VacacionesDias, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-3">
#Html.EditorFor(model => model.VacacionesDias, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.VacacionesDias, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-5">
#Html.LabelFor(model => model.FechaInicio, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-5">
<input type="date" id="fechaInicio" name="fechaInicio" class="Filtros form-control input-sm" />
</div>
</div>
<div class="form-group col-md-2">
<div class="col-md-offset-2 col-md-3">
<input type="submit" value="Solicitar" class="btn btn-success" />
</div>
</div>
</div>
</div>
}
When I use the form and hit the submit button or the application goes to Index or to the same view again
It´s like EF went broke or something
I´ve added that, an error comes out The 'CrearSolicitud' view or its master view is not found or there is no search engine that supports the search locations. We searched in the following locations:
~/Views/Solicitudes/CrearSolicitud.aspx
~/Views/Solicitudes/CrearSolicitud.ascx
~/Views/Shared/CrearSolicitud.aspx
~/Views/Shared/CrearSolicitud.ascx
~/Views/Solicitudes/CrearSolicitud.cshtml
~/Views/Solicitudes/CrearSolicitud.vbhtml
~/Views/Shared/CrearSolicitud.cshtml
~/Views/Shared/CrearSolicitud.vbhtml
#Nemanja I certainly don´t have that view, if I use the same name on the post and no the get, the application goes to the get part again
I have the solution.
The thing is, index is for showing a list of added registries, when it is changed for something else you can´t see that list and that leads you to wrong conclusions.
The routing is working fine, the program is doing what is supposed to do, the RedirectToAction("Index") is ok.
The lesson is, take a while and think about what are you changing and try to follow the VS way of doing things.
I´ve tested now and it´s working
ApplicationDbContext db = new ApplicationDbContext();
// GET: Solicitudes
public ActionResult Index()
{
return View();
}
public ActionResult Index2()
{
return View(db.Solicitudes.ToList());
}
//Get
public ActionResult Solicitud()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Solicitud(Solicitudes s)
{
try
{
if (ModelState.IsValid)
{
s.FechaFinal = DateTime.Now;
s.FechaYHoraSolicitud = DateTime.Now;
s.Id = "e17cba68-0a0b-4d6e-abaf-8026cb91fcd1";
s.fk_tipo_transaccion = 3;
s.fk_estado_solicitud = 1;
db.Solicitudes.Add(s);
db.SaveChanges();
ViewBag.Message = "Solicitud guardada";
ModelState.Clear();
return RedirectToAction("Index2");
}
return View("ModelStateError");
}
//catch
catch (Exception ex)
{
//throw ex;
Console.WriteLine(ex.Message);
return View("Error");
}
}
Related
I am displaying a dropdown list from my controller as follows:
public ActionResult Index()
{
var title = new List<String>()
{
"English", "French", "Spanish"
};
List<SelectListItem> languageList = new List<SelectListItem>();
string defaultTitle = "Language";
foreach (var item in title)
{
languageList.Add(new SelectListItem()
{
Text = item,
Value = item,
Selected = (item == defaultTitle ? true : false)
});
}
ViewBag.LanguageList = languageList;
return View();
}
My View is as follows:
#using (Html.BeginForm("GetStatusTrad", "StatusTradController", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Translation</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("Language")
#Html.DropDownList("lang", new SelectList(ViewBag.LanguageList, "Text", "Value"), "Language")
</div>
</div>
<div></div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
It displays the dropdown correctly, but when I want to pass the selected value to an action of the controller, I get a 404 error.
My action is :
public ActionResult GetStatusTrad(string language)
{
*some code*
}
Any idea why I can't pass the selected value of the dropdown to the controller?
Your helper should be:
#Html.DropDownList("language", <-- note this
new SelectList(ViewBag.LanguageList, "Text", "Value"), "Language")
It happend becose basically your helper will be rendered to input like this:
<select name="language">
...
</select>
And on form POST your controller will be able to bind your values based on name property of input.
#Html.DropDownList("lang", new SelectList(... generates a <select> with name="lang. You need to change the parameter in the POST method to match
public ActionResult GetStatusTrad(string lang)
As a side note, LanguageList is already IEnumerable<SelectListItem> so using new SelectList() to create another identical one is pointless. I can be just
#Html.DropDownList("lang", (IEnumerable<SelectListItem>)ViewBag.LanguageList, "Language")
You also have a typo in the BeginForm() method. It needs to be
#using (Html.BeginForm("GetStatusTrad", "StatusTrad", FormMethod.Post))
i.e. "StatusTrad", not "StatusTradController" (unless you have really named your controller StatusTradControllerController)
you can use strongly type view to return selected dropdown value.
create simple class like below
public class myModel
{
public string language { get; set; }
....
....
}
Then use this class/model in View
#model yourProject.Models.myModel
<div class="form-group">
<label class="col-lg-2 control-label">Language</label>
<div class="col-lg-5">
#Html.ValidationMessageFor(m => m.language)
#Html.DropDownListFor(m => m.language, new SelectList(ViewBag.LanguageList, "Text", "Value"), "-- Select --", new { #class = "form-control" })
</div>
</div>
Controller method look like below
[HttpPost]
public ActionResult GetStatusTrad(myModel model)
{
*some code*
}
I am having problems when I have a model in my navigation partial and a model in my registration view (which of course is in #RenderBody()
This is the error I am getting
The model item passed into the dictionary is of type 'ProfessionalDev.Models.Registration', but this dictionary requires a model item of type 'ProfessionalDev.Models.Login'.
Line 14: <body>
Line 15:
Line 16: #Html.Partial("_Navigation") <=== THE ERROR IS HERE
Line 17: <div class="top-bg"></div>
Line 18: <div class="container body-content">
My layout if as follows
#Html.Partial("_Navigation")
<div class="top-bg"></div>
<div class="container body-content">
#Html.Partial("_Header")
<main>
#RenderBody()
</main>
<footer>
<p>Copyright © 2009-#DateTime.Now.Year Company</p>
</footer>
</div>
The _Navigation partial where I have a Login model because of the Login form
#model ProfessionalDev.Models.Login
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
...
<ul class="dropdown-menu">
<li>
#Html.Partial("_Messages")
#using (Html.BeginForm("Index", "Home", FormMethod.Post)) {
#Html.ValidationMessageFor(model => model.Email)
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", #placeholder = "Email" })
#Html.ValidationMessageFor(model => model.Passwd)
#Html.PasswordFor(model => model.Passwd, new { #class = "form-control", #placeholder = "Password" })
<input type="submit" value="Submit" name="action:Login" class="btn btn-primary btn-sm" />
}
</li>
<li role="separator" class="divider"></li>
<li>Forgot Password?</li>
</ul>
...
Then I have the Registration view with a Registration model
#model ProfessionalDev.Models.Registration
#{
ProfessionalDev.Library.IdentifierTypeItems identifierTypes = new ProfessionalDev.Library.IdentifierTypeItems();
}
<h1>New User Account</h1>
<hr />
#using (Html.BeginForm("Index", "Registration", FormMethod.Post)) {
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.FirstName, "First Name", new { #class = "control-label" }) <span class="required">* </span>
#Html.ValidationMessageFor(model => model.FirstName)
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control" })
</div>
...
<input type="submit" value="Register" name="action:Register" class="btn btn-primary" />
}
RegistrationController
public class RegistrationController : Controller
{
// GET: Registration
public ActionResult Index()
{
return View();
}
[HttpPost]
[MultipleButton(Name = "action", Argument = "Register")]
public ActionResult Index(Registration reg) {
if (ModelState.IsValid) {
...
return RedirectToAction("Index", "Home");
}
return View("Index", reg);
}
}
When I click the Register button and the Registration object is invalid, as you can see above is supposed to return reg to the Registration/Index view, but instead is returning the view to the Home/Index view from the _Navigation partial
HomeController
public class HomeController : Controller
{
[HttpPost]
[MultipleButton(Name = "action", Argument = "Login")]
public ActionResult Index(Login login)
{
...
return View("Index", login);
}
(I hope I am making sense...)
How can I fix this?
This is how it looks from GUI. The Login in the top menu and the register page
You get redirected to because you using #using (Html.BeginForm("Index", "Home", FormMethod.Post)) inside your main view and doesn't matter what is inside your partial view.
Besides, Only way you could call partial view method inside a main view is jQuery.
The best approach is using a ProfessionalDev.Models.Login type property inside your ProfessionalDev.Models.Registration.
Then use your Html.BeginForm for login inside the registration view.
I have the following view:
#model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
#{
ViewBag.Title = Resources.Edit;
}
<h2>#Resources.EditRole</h2>
#Html.ActionLink(Resources.ListRoles, "Index") | #Html.ActionLink(Resources.ManageUserRoles, "ManageUserRoles")
<hr />
<div class="row">
<div class="col-md-8">
<section id="editRoleForm">
#using (Html.BeginForm("Edit", "Role", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>#Resources.Role</h4>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="#Resources.Save" class="btn btn-default" />
</div>
</div>
}
</section>
</div>
</div>
I also have the following two methods in my RoleController:
//
// GET: /Role/Edit/5
public ActionResult Edit(string Role)
{
var thisRole = context.Roles.Where(r => r.Name.Equals(Role, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
return View(thisRole);
}
//
// POST: /Role/Edit/5
[HttpPost]
public ActionResult Edit(FormCollection collection)
{
try
{
var thisRole = context.Roles.Where(r => r.Id.Equals(collection["Id"])).FirstOrDefault();
thisRole.Name = collection["Name"];
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Originally, I was trying to use this method instead of the second one:
//
// POST: /Role/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IdentityRole Name)
{
try
{
context.Entry(Name).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
But I never got it to work because the Name parameter was always null -which I still don't know why it happened, so if someone can explain it to me that'll be greatly appreciated.
I wrote then the other method since I saw the use of FormCollection in another example (to create roles) and it seems to work fine, at least it contains the information I need when I debug it. My issue is that although collection["id"] has the right Id for the Role I'm trying to edit, context.Roles is completely empty. This makes no sense to me given that when the first method is called (loading the View for the first time), this line
var thisRole = context.Roles.Where(r => r.Name.Equals(Role, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
returns the selected role (out of the several that exist and that I can see when I add to watch context.Roles). However, after the view is loaded, the textbox edited and the second method in the controller gets called, context.Roles has nothing in it. Why?
Ok you can use the already built in [Authorize(Roles="RoleType")] filter.
You then have your regular User model and Account controller so you can then authorize users. Once you have authorised them you can set them to a specific role.
E.g. user story: only admins can access action result x
[Authorize(User="Admin")]
Public ActionResult X(){
...
}
That way you simply assign user roles in the model creation.
E.g.
Public Class UserModel
{
int id {get;set;}
string name {get;set;}
string Role {get;set;}
.....
}
Now only users that have been authorised AND are of Role type "Admin" will be able to access that controller.
If you want to edit their role you can do a simple edit user action method
e.g.
[Post]
public actionresult edituser(int? id)
{
if (id == null)
{
return HttpNotFound();
}
using (var db = new UserContext())
{
UserModel editUser = db.UserModel.Find(id);
if (editUser == null)
{
return HttpNotFound();
}
db.User(editModel).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
RedirectToAction("Action", "Controller");
}
Now any user that is NOT of Role type "Admin" will not be able to access that screen. They will receive a 404 error.
I am attempting to render a partial view that contains a simple html form. I want to render the form from a controller as I handle the postback from an overloaded controller method. I have tried #Html.Action("ContactForm")but I get an Exception because child actions cannot redirect.
My Controller:
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult ContactForm()
{
return PartialView(new ContactForm());
}
[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
return RedirectToAction("FormResults", new { ContactForm = Contact });
}
public ActionResult FormResults(ContactForm Contact)
{
return PartialView(Contact);
}
My Form:
#using(Html.BeginForm())
{
<h2>Contact Form</h2>
<div class="input-group">
<h4>#Html.LabelFor(m => m.FirstName, "First Name")</h4>
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control", #placeholder = "First Name" })
</div>
<div class="input-group">
<h4>#Html.LabelFor(m => m.LastName, "Last Name")</h4>
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control", #placeholder = "Last Name" })
</div>
<div class="input-group">
<h4>#Html.LabelFor(m => m.Email, "Email")</h4>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #placeholder = "Email", #type = "text" })
</div>
<input type="submit" class="btn btn-info" value="Submit" />
}
Any Help on how I would accomplish this would be appreciated.
try surrounding the form with a div and a certain id and use:
#using(Ajax.BeginForm("ContactForm","YourController",new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "yourCertainId",
HTTPMethod = "POST"
})
and your ActionMethod:
[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
return Partial("YourPartialName", Contact });
}
make sure that you include the bundle jqueryval on the bottom of your view.
you wont need the second controller method "FormResults"
Does something like this not work for you?
I don't think you need a redirect.
[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
return PartialView("FormResults", Contact);
}
This uses the
PartialView(string viewName, object model)
overload of the PartialView method in the Controller class.
This allows you to use a View that doesn't match the ActionResult's method name.
The same thing works for the plain "View" method as well.
My Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(BlogCompModel blogmodel)
{
if (ModelState.IsValid)
{
...
}
}
My View:
#model BlogProject.Models.BlogCompModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
...
<div class="form-group">
#Html.LabelFor(model => model.BlogCompModel.posts, "Property", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.posts, new MultiSelectList(Model.posts, "post_ID", "postTitle"))
#Html.ValidationMessageFor(model => model.posts.posts)
</div>
</div>
}
Error message on post:
"The parameter conversion from type 'System.String' to type 'BlogProject.Models.Posts' failed because no type converter can convert between these types."} System.Exception {System.InvalidOperationException}
As you can see, I'm not sure how to translate the HTML Multiselect list from a collection of Post_IDs to an ICollection of posts.
Thanks!
You can add another property in your BlogCompModel Model, it'll wrap all selected post in it.
public class BlogCompModel
{
//
public string[] selectedPosts { get; set; }
}
Then in your view:
#Html.ListBoxFor(model => model.selectedPosts ,
new MultiSelectList(Model.posts, "post_ID", "postTitle"))
#Html.ValidationMessageFor(model => model.selectedPosts )
In my blog MVC app, I've a multiselect for Tags and here how I add those to Post in Create action.
Index.cshtml
#model MyBlog.Core.Post
#Html.ListBox("PostTags", (MultiSelectList)ViewBag.MultiSelectList, new { #class = "form-control" })
controller
public ActionResult CreatePost([Bind(Include = "Id,Title,ShortDescription,Description,Published,PostedOn,ModifiedOn,CategoryId")] Post post, int[] postTags)
{
if (postTags != null)
{
foreach (var t in postTags)
{
var tag = _dbTag.GetById(t);
post.Tags.Add(tag);
}
}
// save to database and other stuff
return View(post);
}