I am trying to pass the selected item in a dropdown list back to the controller to fire a stored procedure.
Controller that populates the list:
public ActionResult Activate()
{
var query = db.Certificates
.Where(a => a.Active == "Y")
.Select(cer => cer.CertificateNumber.Substring(0, 4))
.Distinct()
.OrderBy(cer => cer);
ViewBag.BoxNumber = new SelectList(query.ToList());
return View();
}
View I want tet the value from.
#{
ViewBag.Title = "Activate";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.DropDownList("BoxNumber", String.Empty)
<input type="submit" value="Activate" class="btn btn-default" />
}
Action I want to use it in:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Activate(string BoxNumber)
{
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["GrandCelebration"].ConnectionString);
var command = new SqlCommand("ActivateCertificates", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#BoxNumber", BoxNumber);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
return RedirectToAction("Activate");
}
The selected item is not being returned.
Related
Controller
[ActionName("Index")]
[HttpPost]
public ActionResult IndexPost(string button, int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string buttonClicked = Request.Form["SubmitButton"];
if(buttonClicked == "Accept")
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "APPROVED";
db.SaveChanges();
}
else if(buttonClicked == "Decline")
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "UNAPPROVED";
db.SaveChanges();
}
//Save Record and Redirect
return RedirectToAction("Index");
}
Index View
<button type="submit" name="SubmitButton" value="Approve" class="btn btn-sm btn-success">Approve</button>
<button type="submit" name="SubmitButton" value="Unapprove" class="btn btn-sm btn-danger">Unapprove</button>
In my Index view, i have a table where there are rows of data i can "Approve" or "Disapprove" using 2 buttons. I tried using these http://www.scriptscoop.net/t/b7bd27aee268/c-asp-net-mvc-two-different-buttons-in-form-submit.html and ASP.NET MVC two different buttons in form submit. I want the status value to change to Approve or Disapprove when the user clicks the corresponding button. But I'm not sure why it isn't working as I tried to code it similarly to the Edit view.
You can get the value of the submit button as a parameter to your Action method, now all you have to do is compare its value inside the Action and perform the changes you need . In your view the value of the buttons are value="Approve" for the Approve button and value="Unapprove" for the Unapprove button whereas you are comparing it with "Accept" and "Decline".
[ActionName("Index")]
[HttpPost]
public ActionResult IndexPost(string SubmitButton, int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string buttonClicked = SubmitButton;
if(buttonClicked == "Approve")
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "APPROVED";
db.SaveChanges();
}
else if(buttonClicked == "Unapprove")
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "UNAPPROVED";
db.SaveChanges();
}
//Save Record and Redirect
return RedirectToAction("Index");
}
In your HTML, the values for Approve and Unapprove buttons are Approve and Unapprove respectively. However, in your code, you are comparing buttonClicked with Accept and Decline.
It should be like this:
[ActionName("Index")]
[HttpPost]
public ActionResult IndexPost(string button, int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
string buttonClicked = Request.Form["SubmitButton"];
if(buttonClicked == "Approve") // value of Approve button
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "APPROVED";
db.SaveChanges();
}
else if(buttonClicked == "Unapprove") // value of Unapprove button
{
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = "UNAPPROVED";
db.SaveChanges();
}
//Save Record and Redirect
return RedirectToAction("Index");
}
you can try this ;
Controller:
[ActionName("Index")]
[HttpPost]
public ActionResult IndexPost(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var result = Request.Form["result"];
CurrentApplication currentApplication = db.CurrentApplications.Find(id);
currentApplication.AppStatus = result;
db.SaveChanges();
//Save Record and Redirect
return RedirectToAction("Index");
}
View
<input type="hidden" name="result" id="result" />
<a data-value="Approve" class="btn btn-sm btn-success submitButton">Approve</a>
<a data-value="Unapprove" class="btn btn-sm btn-danger submitButton">Unapprove</a>
Javascript
<script>
$('.submitButton').on('click', function (e) {
e.preventDefault();
$('#result').val($(this).data('value'));
$('form').submit();
});
</script>
I have two ActionResults and I am trying to just simply pass an int id from one ActionResult to another. I attempted to use tempdata, but after looking at the value from the debugger the value was zero. The tempdata example I looked at used redirecttoaction(). Can this be done with returnview()?
public ActionResult Details(int? id)
{
myEMSurvey mySurvey = db.myEMSurveys.Find(id);
if (mySurvey == null)
{
return HttpNotFound();
}
SurveyViewModel svm = new SurveyViewModel();
svm.mySurvey = mySurvey;
svm.Questions = (from s in db.myEMSurveyQuestions
where s.SurveyID == id
select s).ToList();
svm.Options = (from o in db.myEMQuestionOptions
where o.SurveyID == id
select o).ToList();
svm.Anwsers = (from a in db.myEMSurveyAnswers
where a.SurveyID == id
select a).ToList();
int intid = id.Value;
TempData["ID"] = intid;
return View(svm);
}
[HttpPost]
public ActionResult CsvDownload()
{
int id = Convert.ToInt32(TempData["ID"]); //value of id=0, TempData["ID"] = 33
var Anwsers = (from a in db.myEMSurveyAnswers
where a.SurveyID == id
select a).ToList();
//id = 0
}
CsvDownload in Details view:
#using (Html.BeginForm("CsvDownload", "Survey", FormMethod.Post))
{
<div class="text-center">
<input type="submit" name="button" value="Download" class="btn btn-success" />
</div>
<br />}
The error in my code was the convert to int32.
Instead I needed to convert like so:
int id = (int)(TempData["ID"]);
This is known as "unboxing". It's a straight cast from object to int.
I'm new to ASP.NET MVC. I want to use selected items from my dropdownlist to search my database table. The dropdownlist was generated from a BOL model which automatically binds to the view.
Below are my code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL;
using BOL;
namespace DentiCareApp.Areas.Admin.Controllers
{
[AllowAnonymous]
public class GenerateInvoiceController : Controller
{
private TreatmentBs objBs;
public GenerateInvoiceController()
{
objBs = new TreatmentBs();
}
// GET: Admin/GenerateInvoice
public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");
if (CompanyID == null)
{
return View();
}
else
{
return View(db.Treatments.Where(x => x.Company == CompanyID.Take(50)));
}
//return View();
}
Also below is the interface of view.
Secondly, I also want the search result to appear on the same page. How do I do this? If I create a separate action for this, I will need to create a separate view for it. Can partial view be used? If so how?
Below is the code to the View
#model BOL.GenerateInvoice
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p></p>
<p></p>
<p></p>
<h2>Quickly Generate Invoice</h2>
#using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
#Html.AntiForgeryToken()
<div class="">
<div>
#Html.DropDownList("MyCompany.CompanyId", (IEnumerable<SelectListItem>)ViewBag.CompanyId, "Select Company", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MyCompany.CompanyId, "", new { #class = "text-danger" })
<input type="submit" value="Search" class="btn btn-primary" />
</div>
</div>
}
Try this.
Controller action:
public ActionResult Index(string CompanyID)
{
DentiCareEntities db = new DentiCareEntities();
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName", CompanyID); // preselect item in selectlist by CompanyID param
if (!String.IsNullOrWhiteSpace(CompanyID))
{
return View();
}
return View(db.Treatments.Where(x => x.CompanyID == CompanyID).Take(50));
}
View code:
#model IEnumerable<Treatment>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Quickly Generate Invoice</h2>
#using (Html.BeginForm("Index", "GenerateInvoice", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.DropDownList("CompanyId", (SelectList)ViewBag.CompanyId, "Select Company", new { #class = "form-control" })
<input type="submit" value="Search" class="btn btn-primary" />
}
#if(Model != null && Model.Any())
{
foreach(var item in Model)
{
#Html.DisplayFor(model => item)
}
}
You can change the DisplayFor() here to show individual properties of the given Treatment, such as #Html.DisplayFor(model => model.TreatmentID) and such
The Above code worked for me but with little tweaks. Here are few modification I made to your code.
The parameter in the Index Action was changed from string to integer.
The Optional Parameter in the ViewBag.CompanyId was removed.
Lastly, the line if (!String.IsNullOrWhiteSpace(CompanyID)) and changed to if (CompanyID == 0) { return View(treatmentList);}
The result however is great as it worked like a charm! Thanks for your help!
// GET: Admin/ListTreatment
public ActionResult Index(string sortOrder, string sortBy, string Page, int CompanyID = 0)
{
ViewBag.sortOrder = sortOrder;
ViewBag.sortBy = sortBy;
var treatmentList = objBs.GetALL();
//ViewBag.employeeCompany = employeeCompany.Distinct();
switch (sortOrder)
{
case "Asc":
treatmentList = treatmentList.OrderBy(x => x.TreatmentDate).ToList();
break;
case "Desc":
treatmentList = treatmentList.OrderByDescending(x => x.TreatmentDate).ToList();
break;
default:
break;
}
ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "CompanyName");
ViewBag.TotalPages = Math.Ceiling(objBs.GetALL().Where(x=>x.CompanyId > 0).Count()/10.0);
int page = int.Parse(Page == null ? "1" : Page);
ViewBag.Page = page;
treatmentList = treatmentList.Skip((page - 1) * 10).Take(10);
if (CompanyID == 0)
{
return View(treatmentList);
}
return View(db.Treatments.Where(x => x.CompanyId == CompanyID).Take(50));
}
First : for entity framework id should be nullable, so it can be accepted as argument, the action parameter should be int? CompanyID
Second : the comparison is not correct with (CompanyID == 0)
It should be (CompanyID == null)
I am developing a project in ASP.net MVC. In my registration form, I have a checkbox where I select the items you would like to add to the database. My form of editing, I have to get these checked items and show the view: all items that are in the grid and the fields that were selected are saved in the database. I would like to return to the View all checked items that are saved in the database.
The code looks like this:
#using Forte.Rastreador.ViewModels
#using GridMvc.Html
#model SuperModulosPerfilUsuarioViewModel
<fieldset>
#Html.Label("Nome do Perfil: ")
#Html.TextBoxFor(u => u.Descricao)
<br /><br />
</fieldset>
<fieldset> //minha checkBOX
<legend>Modulos do Sistema</legend>
#Html.Grid(Model.ModulosSistemas).Columns(columns =>
{
columns.Add()
.Encoded(false)
.Sanitized(false)
.SetWidth(30)
.RenderValueAs(o => Html.CheckBox("Checked", #Model.Check, new { value = o.CodModulo }));
columns.Add(u => u.DesModulo)
.Titled("Modulos Perfil")
.Encoded(false);
})
//Action metodo get Editar, onde retorna todo o conteudo de visualizacao para a view.
public ActionResult EditarPerfilUsuario(int CodPerfil)
{
var perfilUsuario = PerfilUsuarioRepositorio.ObterPerfilUsuarioPorCodigo(CodPerfil);
var perfilUsuarioVM = new SuperModulosPerfilUsuarioViewModel();
perfilUsuarioVM.Descricao = perfilUsuario.Descricao;
perfilUsuarioVM.ModulosSistemas = ModulosSistemaRepositorio.ListarModulosSistemas();
perfilUsuarioVM.ModulosDoPerfil = ModulosPerfilRepositorio.ListarModulosDoPerfisPorCodPerfil(CodPerfil);
foreach (var ms in perfilUsuarioVM.ModulosSistemas)
{
foreach (var mp in perfilUsuarioVM.ModulosDoPerfil)
{
if (ms.CodModulo == mp.CodModulo)
{
perfilUsuarioVM.Check = true;
}
}
}
return View("EditarPerfilUsuario", perfilUsuarioVM);
}
public IEnumerable<ModulosSistema> ListarModulosSistemas() //metodos listar que se encontram no meu repositorio
{
return this.Context.ModulosSistemas;
}
public IEnumerable<ModulosDoPerfil> ListarModulosDoPerfisPorCodPerfil(int CodPerfil)
{
return this.Context.ModulosDoPerfil.Where(c=>c.CodPerfil==CodPerfil);
}
In the create view what i am trying to do is when you choose a name from the dropdown list to fill the Login html.TextBoxFor automatically with his details.
Currently the Login textbox remains empty when i choose a person from dropdown list.
So i ve got my json object and tested as well my sql which is fine so i suppose the issue must be somewhere in jquery.
I would be glad if you could help me find the error.
View :
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">#Html.LabelFor(model => model.UserLogin)</div>
<div class="editor-field">#Html.TextBoxFor(model => model.UserLogin, new {id ="LoginId" })
#Html.ValidationMessageFor(model => model.UserLogin)</div>
<div class="editor-label">#Html.LabelFor(model => model.UserFullName)</div>
<div class="editor-field">#Html.DropDownList("UserFullName", ViewBag.UserFullName as SelectList, "Select a User", new { id = "UserID" })
#Html.ValidationMessageFor(model => model.UserFullName)</div>
<p>
<input type="submit"
value="Create" />
</p>
</fieldset> }
<div>#Html.ActionLink("Back to List", "Index")</div>
<script type="text/javascript">
$('#UserID').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetUserForm")',
data: { FullName: $('#UserID').val() },
success: function (results){
var login = $('#LoginId');
login.empty();
$.each(results, function ()
{
login.val(this.ID).text(this.Value);
});
}});
});
</script>
Controller:
public ActionResult Create()
{
var names = StaffDB.StaffData.AsEnumerable().Select(s => new
{
ID = s.ID,
FullName = string.Format("{0} {1}", s.Forename1, s.Surname)
}).ToList();
if(ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserFullName = new SelectList(names, "FullName", "FullName", user.UserFullName);
return View(user);
}
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new
{
Value = s.Login,
ID = s.ID
};
return Json(data);
}
I think the issue is while returning the json, In MVC by default Jsonresult is "Deny get", so you have add "Allow Get".
[HttpPost]
public JsonResult GetUserForm(string FullName)
{
//pseudo code
var data = from s in StaffDB.StaffData
where s.Forename1 + ' ' + s.Surname == FullName
select new { Value = s.Login, ID = s.ID };
if (data == null)
return Json(null);
return Json(data , JsonRequestBehavior.AllowGet);
}