My create button isn't working when clicked on. Can someone please tell me where I went wrong?
I tried a few forums but they haven't solved the issue.
Controller:
using Rentals.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Rentals.Controllers
{
public class GenreController : Controller
{
private ApplicationDbContext db;
public GenreController()
{
db = new ApplicationDbContext();
}
// GET: Genre
public ActionResult Index()
{
return View(db.Genres.ToList());
}
//getaction
public ActionResult Create()
{
return View();
}
//post action to insert data into database
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Genre genre)
{
if (ModelState.IsValid)
{
db.Genres.Add(genre);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
protected override void Dispose(bool disposing)
{
db.Dispose();
}
}
}
View (create.cshtml):
#model Rentals.Models.Genre
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
}
<div class="form-horizontal">
<h3> Create new Genre</h3>
<hr />
<div class="form-group">
#Html.LabelFor(m=>m.Name, htmlAttributes: new { #class ="control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(m=>m.Name, new {htmlAttributes = new {#class="form-control"}})
#Html.ValidationMessageFor(m=>m.Name,"", new { #class = "text-danger"})
</div>
</div>
</div>
<div>
<input type="submit" value="Create" class="btn btn-sm btn-success" />
#Html.Partial("_BackToListPartial")
</div>
When I click on the create button it should add to the database. For some reason when I click it, it's not doing anything.
Wrap the form around your HTML.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h3> Create new Genre</h3>
<hr />
<div class="form-group">
#Html.LabelFor(m=>m.Name, htmlAttributes: new { #class ="control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(m=>m.Name, new {htmlAttributes = new {#class="form-control"}})
#Html.ValidationMessageFor(m=>m.Name,"", new { #class = "text-danger"})
</div>
</div>
</div>
<div>
<input type="submit" value="Create" class="btn btn-sm btn-success" />
#Html.Partial("_BackToListPartial")
</div>
}
Related
I have a Search Partial View that I want to return but I want to return it by running it through an exisiting Partial View Result in the Controller instead of loading the view directly.
So, in the controller I have:
public ActionResult Index()
{
return View();
}
public PartialViewResult _GetSearch(List<Search> model)
{
return PartialView("_Search", model);
}
[ValidateAntiForgeryToken()]
public PartialViewResult _BeginSearch(string search)
{
var results = SearchModels(search).ToList();
return PartialView("_GetSearch", results);
}
And in the search view itself I have:
<div class="col-md-4">
<div id="modelSearch" class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-search"></i> Search by Model / Manufacturer</h3>
</div>
<div class="panel-body">
#using (Ajax.BeginForm("_BeginSearch", "Home", new AjaxOptions() { UpdateTargetId = "modelSearch" }))
{
#Html.AntiForgeryToken()
<div class="input-group">
#Html.TextBox("search", null, new {id = "name", #class = "form-control", placeholder = "Please enter a manufacturer or model"})
<span class="input-group-btn">
<button id="search" class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
</span>
</div>
if (Model != null)
{
<div class="searchResults fade">
#foreach (var s in Model)
{
<div class="result">
#switch (s.ResultType)
{
case "Man":
#s.Manufacturer
break;
case "Mod":
#s.Manufacturer #s.Model
<img src="~/Images/General/(#s.TierId).png" alt="Tier #s.TierId"/>
break;
}
</div>
}
</div>
}
}
</div>
</div>
</div>
When I try and run the code it tell me that it cannot find the _GetSearch view, which yes technically is right, but I'm not looking for a view I'm looking for a method in the controller.
I have a IdentityUser Model
I have a Manage View with 3 partials (each one have one viewmodel and controller) I want to enter on this view and see the forms with data filled of the model.
ApplicationUser : IdentityUser (Model of my user)
using Microsoft.AspNet.Identity.EntityFramework;
using System;
namespace MTGWeb.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public String Pais;
public String Email;
public DateTime UltimoLogin;
public DateTime FechaRegistro;
public String Tipo;
public Boolean Activado;
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
}
Manage (Main View)
#using MTGWeb.Models;
#using Microsoft.AspNet.Identity;
#{
ViewBag.Title = "Administrar cuenta";
}
<h2>#ViewBag.Title.</h2>
<p class="text-success">#ViewBag.StatusMessage</p>
<div class="row">
<div class="col-md-12">
<p>Ha iniciado sesión como <strong>#User.Identity.GetUserName()</strong>.</p>
#Html.Partial("_ChangePasswordPartial")
#Html.Partial("_ChangeEmailPartial")
#Html.Partial("_OtherFieldsPartial")
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
_ChangeEmailPartial
#using Microsoft.AspNet.Identity
#model MTGWeb.Models.ManageUserViewModelEmailChange
#using (Html.BeginForm("ManageEmail", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Formulario para cambiar email</h4>
<hr />
#Html.ValidationSummary()
<div class="form-group">
#Html.LabelFor(m => m.OldEmail, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.OldEmail, new { #class = "form-control", Value = Model.OldEmail})
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.NewEmail, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.NewEmail, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmEmail, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ConfirmEmail, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Cambiar email" class="btn btn-default" />
</div>
</div>
}
Controller - ManageEmail
// Cambia el email
// POST: /Account/ManageEmail
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ManageEmail(ManageUserViewModelEmailChange model)
{
ViewBag.ReturnUrl = Url.Action("Manage");
var user = await UserManager.FindByNameAsync(User.Identity.Name);
if (ModelState.IsValid)//Si no hay errores en la validación que hace la clase (Datatype, length, required, etc..)
{
if (model.OldEmail.Equals(model.NewEmail) && model.OldEmail.Equals(user.Email))
{
user.Email = model.NewEmail;
IdentityResult success = await UserManager.UpdateAsync(user);
if (success.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangeEmailSuccess });
}
}
}
//Si el modelo no es válido o no el cambio no ha tenido exito
return View(model);
}
I have 2 more controllers for others partials, but this is usefull for the example. These Model.OldEmail is null and causes a Nullreference error, Where I have to fill it? I guess that this have to be filled in AccountController/Manage, but.. How can I send it to the partials?
I am new on MVC and .NET, I used to work with Java, and I am stucked in this (Is a testing project purposes)
pass the model you want the partials to show into the partials as an argument
you will need to add a viewmodel containing the models you want to show to the host view.
eg
#Html.Partial("_ChangePasswordPartial",Model.ChangePAsswordViewModel)
Model is a property on Controller (which your manage controller will inherit from)
You pass the viewmodel into the manage view from the controller in return View(YourViewModelInstance) from your Manage controller method.
you also need to add a reference to that model in your manage form like you have in your partials
Eg
#model MTGWeb.Models.ManageViewModel
your manage viewmodel might look something like
public class ManageViewModel
{
public ChangePasswordViewModel ChangePasswordViewModel{get;set;}
public NextViewModel NextViewModel{get;set;}
public AnotherViewModel NextViewModel{get;set;}
}
I've created a page that uses entity framework to retrieve/Display info in the database I've also got create functionality in a partial view on the same page but it doesn't save/insert data.
Here is my Home View:
#model IEnumerable<TerminalHost.Models.buildingInfo>
#{
ViewBag.Title = "Home Page";
}
<h3>We suggest the following:</h3>
<ol class="round">
<li class="one">
<h5>Please begin creating your network structure:</h5> <button id="modal-opener">Add a new building</button>
</li>
<li class="two">
</li>
</ol>
<div class="Container">
<div class="Box1">
#foreach (var item in Model)
{<div>
<h4 class="Heading">#item.buildingName</h4>
<h4 class="Heading">#item.buildingNumber</h4>
<p>#item.buildingDesc1</p>
<p>#item.buildingDesc2</p>
<p>#item.buildingDesc3</p>
</div>
}
</div>
</div>
<div id="Modal" title="Building Details">
#Html.Partial("buildForm", new TerminalHost.Models.buildingInfo())
</div>
Here is my partial View:
#model TerminalHost.Models.buildingInfo
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>buildingInfo</legend>
<div class="editor-label">
#Html.LabelFor(model => model.buildingNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.buildingNumber)
#Html.ValidationMessageFor(model => model.buildingNumber)
</div>
....
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
And This is my controller:
public class HomeController : Controller
{
thDB _db = new thDB();
public ActionResult building()
{
var buildingModel = _db.buildings.ToList();//you have to remove the FirstOrDefault() extension method
return View(buildingModel);
}
public ActionResult buildForm()
{
return PartialView();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult buildForm(buildingInfo buildinginfo)
{
if (ModelState.IsValid)
{
_db.buildings.Add(buildinginfo);
_db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(buildinginfo);
}
protected override void Dispose(bool disposing)
{
if(_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
I've attempted to replicate the same code as the scaffold template that is created to do the CRUD functions but they are separated out into different views whereas I want them all on one page.
What you need it's to tell your partial view the Action to call.
Could you change this line:
#using (Html.BeginForm())
To
#using (Html.BeginForm("builForm","Home"))
And in your Action:
HttpPost]
[ValidateAntiForgeryToken]
public ActionResult buildForm(buildingInfo buildinginfo)
{
if (ModelState.IsValid)
{
_db.buildings.Add(buildinginfo);
_db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView(buildinginfo);//instead of return this you can redirect to Index so you can see the update. Just a suggestion
}
I have troubles with binding my button to an action. I created a form and when user click "send" button it needs to trigger some action.
Below you can see my cshtml code:
#model Project.Models.MailMessage
<form name="contactForm" method="post" action="" class="form-horizontal" role="form">
<div class="col-lg-8">
<div id="Contact" class="jumbotron contact-form">
<div class="panel-heading">
<h1 class="panel-title">Kontakt</h1>
</div>
<div class="input-group">
<span class="input-group-addon">Imie</span>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control" ,placeholder ="Twoje imię"})
<!--<input type="text" class="form-control" placeholder="Imie" id="inputName" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Nazwisko</span>
#Html.TextBoxFor(model => model.Surname, new { #class = "form-control", placeholder = "Twoje nazwisko" })
<!--<input type="text" class="form-control" placeholder="Nazwisko" id="inputSurname" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Email</span>
#Html.TextBoxFor(model => model.EmailAdress, new { #class = "form-control", placeholder = "Adres email" })
<!--<input type="email" class="form-control" placeholder="Email" id="inputEmail" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Treść<br /> wiadomości</span>
#Html.TextAreaFor(model => model.Name, new { #class = "form-control", placeholder = "Treść wiadomości", id = "inputMessage", name = "inputMessage", rows="4" })
<!--<textarea class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Treść wiadomości..." required="required"></textarea>-->
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-1">
<button type="submit" class="btn btn-default">
Send Message
</button>
</div>
</div>
</div>
</div>
</form>
Here is my Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
// GETL /Search/
public ActionResult Search()
{
return View();
}
public ActionResult Contact()
{
return View();
}
public ActionResult SendMail(MailMessage m)
{
return RedirectToAction("Contact");
}
}
I managed to do all this things. All code works. But stucked with I think easies part tof a job. Binding button to call SendMail(MailMessage m) from Controller.
Can anyone suggest me how to do this?
Use Html.BeginForm helper and <input type="submit" value="..." /> within. See an example here. Prefer infrastructure helpers over own HTML code where possible. You probably do not use Antiforgery mechanics to prevent CSRF attacks. It's recommended in post forms, as described in the example.
You have to declare the action of the form.
<form ... action="#Url.Action("SendMail","Home")" ...>
Try this:
SendMail.cshtml
#model Project.Models.MailMessage
<form name="contactForm" method="post" action="" class="form-horizontal" role="form">
<div class="col-lg-8">
<div id="Contact" class="jumbotron contact-form">
<div class="panel-heading">
<h1 class="panel-title">Kontakt</h1>
</div>
<div class="input-group">
<span class="input-group-addon">Imie</span>
#Html.TextBoxFor(model => model.Name, new { #class = "form-control" ,placeholder ="Twoje imię"})
<!--<input type="text" class="form-control" placeholder="Imie" id="inputName" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Nazwisko</span>
#Html.TextBoxFor(model => model.Surname, new { #class = "form-control", placeholder = "Twoje nazwisko" })
<!--<input type="text" class="form-control" placeholder="Nazwisko" id="inputSurname" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Email</span>
#Html.TextBoxFor(model => model.EmailAdress, new { #class = "form-control", placeholder = "Adres email" })
<!--<input type="email" class="form-control" placeholder="Email" id="inputEmail" required="required">-->
</div>
<div class="input-group">
<span class="input-group-addon">Treść<br /> wiadomości</span>
#Html.TextAreaFor(model => model.Name, new { #class = "form-control", placeholder = "Treść wiadomości", id = "inputMessage", name = "inputMessage", rows="4" })
<!--<textarea class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Treść wiadomości..." required="required"></textarea>-->
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-1">
<button type="submit" class="btn btn-default">
Send Message
</button>
</div>
</div>
</div>
</div>
</form>
Here you controller
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
// GETL /Search/
public ActionResult Search()
{
return View();
}
public ActionResult Contact()
{
return View();
}
[HttpGet]
public ActionResult SendMail(MailMessage m)
{
return View();
}
[HttpPost]
public ActionResult SendMail(MailMessage m)
{
return RedirectToAction("Contact");
}
}
When you click on button it call [HttpPost] Method in you controller. It is necessary to mention [HttpPost]
just change your method
[HttpPost]
public ActionResult SendMail(MailMessage m)
{
return RedirectToAction("Contact");
}
I am new to MVC and I am stuck in creating a submit form.
Model Email.cs:
using System.Web;
namespace MySite.Models
{
public class Email
{
public string From { get; set; }
public string Subject { get; set; }
public string body { get; set; }
}
}
Controller CommunicationController.cs:
namespace MySite.Controllers
{
public class CommunicationController : Controller
{
public ActionResult SendEmail() {
Email email = new Email();
return View(email);
}
[HttpPost]
public ActionResult SendEmail(Email email)
{
if (ModelState.IsValid)
{
}
return View(email);
}
}
}
View SendEmail.cshtml:
#model MySite.Models.Email
#{
ViewBag.Title = "SendEmail";
}
<h2>#Html.Label("Send email")</h2>
#using(Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.Label("From")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.From)
</div> <div class="editor-label">
#Html.Label("Subject")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Subject)
</div> <div class="editor-label">
#Html.Label("Body")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.body)
</div>
<input id="btnSubmit" type="submit" value="SendEmail" />
}
When I press submit, the event never gets fired. In the controller if I press 'go to view' then it goes to SendEmail view. I have no idea whats happenning. I tried to debug but the [HttpPost] controller never gets fired.
Here is what I get from browser, I don't see action
<form method="post" action="/" novalidate="novalidate">
<input type="hidden" value="ZktM_I7fzdlcNme4YVEcNNpnFFmQu1cpAuTXarO_V4w-7bPmpHkaLRfNY3cXGMYy7wkRgSJWWSkS8lp5vdRimFrNCgqk0Jfdr4v7Zc3V2pg1" name="__RequestVerificationToken">
<div class="editor-label">
<div class="editor-field">
<input id="From" class="text-box single-line" type="text" value="" name="From">
</div>
<div class="editor-label">
<div class="editor-field">
<div class="editor-label">
<div class="editor-field">
<input id="btnSubmit" type="submit" value="SendEmail">
</form>
Try this,
#using (Html.BeginForm("ActionName", "ControllerName",
FormMethod.Post))
{
//form UI
<input id="btnSubmit" type="submit" value="SendEmail" />
}
Edit
You can also try this:
<a onclick="$('#formId').submit();">Submit</a>
or
<button type="submit">Submit</button>
I rarely use the basic helper, so I could be wrong, but I believe the default method you get from
Html.BeginForm()
is a GET. So, you probably want to use
Html.BeginForm("SendEmail", "Communication", FormMethod.Post, new { /* html attributes */ })
Then, to test whether you're actually hitting the controller, add this inside the action:
ModelState.AddModelError("", "Action was called!");
That will show up as an error in your ValidationSummary, which is okay, since we're just debugging here.
I'm a little late to the party...
Try replacing:
<input id="btnSubmit" type="submit" value="SendEmail" />
With:
<button id="btnSubmit" type="submit" name="submitButton value="SendEmail" />
Let us know if this works, or if you found another solution! :)