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.
Related
I am making a tweak to an app and doing an UPDATE. It throws me the following error:
There is no ViewData item of type 'IEnumerable' that has the key 'Conve'.
My DropDownList loads the data perfectly but when I select any of that list to use its value and change it to the value that is in my BD it throws that error
Model: TableAsign.cs
public class TableAsign
{
public long IdCliente { get; set; }
public string nombre { get; set; }
}
Controller: MastController.cs
[Authorize]
public ActionResult Asign_Conv(int idUsuario)
{
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{ return new SelectListItem()
{ Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
using (TPConveniosEntities db = new TPConveniosEntities())
{
Usuario user = db.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
return View(user);
}
}
In this part it performs the UPDATE and it seems to me that it has to do when I bring the value of my DropDownList with my long variable, it throws me the error and then when I consult my DB I see that if it performs the UPDATE but giving me that error
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IdCliente = Convert.ToInt32(collection["Convenio"].Trim());
user.userName = userName;
user.idCliente = IdCliente;
contexto.SaveChanges();
return View(user);
}
}
VIEW: Asign_Conv.cshtml
#using TPConvenios.App_Data;
#model Usuario
#{
Layout = null;
AjaxOptions ajaxOpciones = new AjaxOptions
{
UpdateTargetId = "cuerpoPopUpGenerico2",
InsertionMode = InsertionMode.Replace,
OnSuccess = "OnSuccess_Asign",
OnFailure = "OnFailure"
};
List<SelectListItem> items = (List<SelectListItem>)ViewBag.items;
}
<div id="contenedor" style="margin: 15px 30px">
#using (Ajax.BeginForm("Asign_Conv", "Mast", null, ajaxOpciones, new { id = "Asign_Conv" }))
{ #Html.ValidationSummary(true);
<input type="hidden" name="idUsuario" id="idUsuario" value="#(null != Model ? Model.idUsuario : 0)" />
<p>
<input name="usuario" type="text" id="usuario" class="usuario" placeholder="Usuario" value="#(null != Model ? Model.userName : String.Empty)"/>
</p>
<p>
#Html.DropDownList("Convenio", items, "Seleccione el Convenio", new { #class = "form-control" })
</p>
<p id="bot">
<input name="submit" type="submit" id="submit" value="Asignar" class="botonNuevo" style="float: right" />
</p>
}
</div>
I managed to solve my problem by bringing me the code with which I load my DropdownList, and pasting it to the POST where it performs UPDATE.
staying this way
[Authorize]
[HttpPost]
public ActionResult Asign_Conv(FormCollection collection)
{
using (TPConveniosEntities contexto = new TPConveniosEntities())
{
var idUsuario = Convert.ToInt32(collection["IdUsuario"].Trim());
Usuario user = contexto.Usuario.FirstOrDefault(u => u.idUsuario == idUsuario);
var userName = collection["usuario"].Trim();
long IDCliente = Convert.ToInt32(collection["Conve"].Trim());
/*********** ESTO FUE LO QUE COPIE PARA QUE FUNCIONARA **********/
List<Models.TableAsign> lst = null;
using (TPConveniosEntities db = new TPConveniosEntities())
{
lst = (from d in db.Cliente
orderby d.nombre
select new TableAsign
{
IdCliente = d.idCliente,
nombre = d.nombre
}).ToList();
}
List<SelectListItem> items = lst.ConvertAll(d =>
{
return new SelectListItem()
{
Text = d.nombre.ToString(),
Value = d.IdCliente.ToString(),
Selected = false
};
});
ViewBag.items = items;
/*************************** HASTA AQUI **********************/
user.userName = userName;
user.idCliente = IDCliente;
contexto.SaveChanges();
return View(user);
}
}
I have a page with information, i want to add there a list (in a form of table) within a partial view. User has to have an ability to sort it by switching radio box.
My problem: the code works fine (i have tried in a separate view), but when i try to switch radio button (they submit page on change and activate 2nd method, which create new model according to radio button) i get html code only from my partial view.
In other words:
i want to : HTML from view1 + HTML from myPartial
i get: only HTML from myPartial
I suppose problem is here (calling my myPartial):
#Html.Action("_ShowEmployeeProjects", "Employee")
But when i try to use this:
#Html.Partial("Partial/_ShowEmployeeProjects")
I get this:
The model item passed into the dictionary is of type
'BTGHRM.Models.EmployeeJobDataViewModel', but this dictionary requires
a model item of type
'System.Collections.Generic.List`1[BTGHRM.Models.EmployeeProjectHistoryModel]'.
My controllers code:
public PartialViewResult _ShowEmployeeProjects()
{
int EmpId = HRMSession.SelectedEmployeeId;
using (var db = new HRMEntities())
{
List<EmployeeProjectHistoryModel> list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId && t1.IsActive == true)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
return PartialView("Partial/_ShowEmployeeProjects",list);
}
}
[HttpPost]
public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
{
int EmpId = HRMSession.SelectedEmployeeId;
List<EmployeeProjectHistoryModel> list;
using (var db = new HRMEntities())
{
if (ActiveOnlySelect.Equals("both"))
{
list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
list.OrderBy(x => x.StartDate);
}
else
{
list = (from t1 in db.ProjectWorkers
join t2 in db.Projects
on t1.ProjectId equals t2.ProjectId
where (t1.WorkerId == EmpId && t1.IsActive == true)
select new EmployeeProjectHistoryModel()
{
ProjectName = t2.ProjectName,
Activity = t1.Activity,
StartDate = t1.StartDate,
EndDate = t1.EndDate
}).ToList();
list.OrderBy(x => x.StartDate);
}
}
return PartialView("Partial/_ShowEmployeeProjects", list);
}
My partial:
#model List<BTGHRM.Models.EmployeeProjectHistoryModel>
#using (Html.BeginForm("_ShowEmployeeProjects", "Employee", FormMethod.Post, new { type = "main" }))
{
<table>
<tr>
<td>
#Html.RadioButton("ActiveOnlySelect", "activeonly", true, new { id = "ActiveOnlySelect0", onchange = "this.form.submit();" })
<label for="ActiveOnlySelect0">#Resources.Localization.show_only_actual</label>
</td>
</tr>
<tr>
<td>
#Html.RadioButton("ActiveOnlySelect", "both", new { id = "ActiveOnlySelect1", onchange = "this.form.submit();" })
<label for="ActiveOnlySelect1">#Resources.Localization.show_all_data</label>
</td>
</tr>
</table>
}
#{
WebGrid grid = new WebGrid(Model, canSort: false, rowsPerPage: 15);
if (Model.Any())
{
#grid.GetHtml(
tableStyle: "table",
headerStyle: "table_HeaderStyle",
footerStyle: "table_PagerStyle",
rowStyle: "table_RowStyle",
alternatingRowStyle: "table_AlternatingRowStyle",
selectedRowStyle: "table_SelectedRowStyle",
columns: grid.Columns(
grid.Column("ProjectName", Resources.Localization.project, style: "p30"),
grid.Column("Activity", Resources.Localization.activity, style: "p30"),
grid.Column("StartDate", Resources.Localization.start_date, format: #<text>
#if (item.StartDate != null)
{
<span class="display-mode"><label id="StartDateLabel">#item.StartDate.ToShortDateString()</label></span>
#Html.Hidden("Model.StartDate", (object)item.StartDate.ToShortDateString())
}
else
{
<span> </span>
}</text>, style: "p10"),
grid.Column("EndDate", Resources.Localization.end_date, format: #<text>
#if (item.EndDate != null)
{
<span class="display-mode"><label id="EndDateLabel">#item.EndDate.ToShortDateString()</label></span>
#Html.Hidden("Model.EndDate", (object)item.EndDate.ToShortDateString())
}
else
{
<span> </span>
}</text>, style: "p10")
)
)
}
}
It looks like you are passing a wrong model to your partial. The structure will be:
In your principal Layout:
#model System.Collections.Generic.List[BTGHRM.Models.your_model]
<!-- DO YOUR HTML´S STUFF. You can access to your_model.employee´s list -->
#Html.Partial("Partial/_ShowEmployeeProjects", Model.projects)
In your Partial, remember to get the model which you are passing from your main layout:
#model System.Collections.Generic.List[BTGHRM.Models.your_model.projects]
<!-- DO YOUR HTML´S STUFF -->
Then, in your controller, you must return return:
[HttpPost]
public PartialViewResult _ShowEmployeeProjects(string ActiveOnlySelect)
{
// DO YOUR MAGIC
// model should be a List[BTGHRM.Models.your_model]
PartialView("Partial/_ShowEmployeeProjects", model);
}
Model:
public class your_model
{
List<Employee> employees;
List<Project> projects;
.....
}
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'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 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.