MVC Razor form : data not sent - c#

I'm trying to so a simple form to send some data. My form have a list of checkboxes and next to each box, a name and a role of person. What I want to do : recover the list of person that box have been checked.
I've created a model that way to do that :
public class CoupleModel
{
public Boolean isSelected { get; set; }
public String name {get; set;}
public String login { get; set; }
public String role { get; set; }
public CoupleModel(String name, String login, String role)
{
this.name = name;
this.login = login;
this.role = role;
this.isSelected = false;
}
public CoupleModel()
{
this.isSelected = false;
}
}
My form looks like this :
#using (Html.BeginForm("CreateInventory", "Home"))
{
#Html.Action("PersonListInventory")
<button type="submit" class="btn btn-primary">Validate creation</button>
}
And the PartialView linked to it is this one :
#model List<MyApp.Models.CoupleModel>
<table class="table table-striped table-bordered"">
<tbody>
#for (int i = 0; i < Model.Count(); i++) {
<tr>
<td>
#Html.EditorFor(m => m[i].isSelected)
</td>
<td>
#Html.EditorFor(m => m[i].name)
</td>
<td>
#Html.EditorFor(m => m[i].role)
</td>
</tr>
}
</tbody>
</table>
And then, in my controller view, I just want to list the name of the people where the box have been checked :
[HttpPost]
public ActionResult CreateInventory(List<CoupleModel> model)
{
String res = "";
foreach (var item in model) {
if (item.isSelected)
{
res += "selected : " + item.login + "<br>";
}
else
{
res += item.login + "<br>";
}
}
ViewBag.Res = res;
return View();
}
But only the "isSelected" part is set, that's to say that login is always blank when displaying. Why isn't it set ? Do I need to do some particular binding ?

that's to say that login is always blank when displaying.
That's perfectly normal. You don't have a corresponding field in your form. You need to add it as a hidden field:
#Html.HiddenFor(m => m[i].login)

You need to add #Html.HiddenFor(..)s for the fields you want to pass along.
The result:
#for (int i = 0; i < Model.Count(); i++) {
#Html.HiddenFor(m => m[i].login)
<tr>
<td>
#Html.EditorFor(m => m[i].isSelected)
</td>
<td>
#Html.EditorFor(m => m[i].name)
</td>
<td>
#Html.EditorFor(m => m[i].role)
</td>
</tr>
}
On the side, please use the .NET naming convention.

Related

ASP.NET MVC Get checkstate from looped, bound checkboxes

in my journey of learning ASP.NET MVC I encounterd another difficulty:
I'm trying to POST a form with 3 checkboxes, the checkboxes are looped onto the form according to a bound PresentationModel.
I don't know what to fill in at the "asp-for" tag-helpers for the checkboxes in the view so they pass a boolean to the "Create()" ActionResult in the controller and to show the values in the "Overview" View.
Currently it passes NULL for al of them, the other aproaches I tried always resulted in an "InvalidCastException" as it has to be a boolean not an "int[]".
PresentationModel (PMRegistration.cs)
public class PMRegistration
{
public List<Device> Devices { get; set; }
}
View (Index.cshtml)
#model Week3_oef2_ITPro.PresentationModel.PMRegistration
<form asp-controller="Register" asp-action="Create" method="post">
<table>
<tr>
<td>Are you wearing any dangerous accessoires</td>
</tr>
#foreach (var item in Model.Devices)
{
<tr>
<td>#item.Name</td>
<td class="form-group">
<input type="checkbox" asp-for="#item.CheckState" value="#item.Id" class="form-control" />
</td>
</tr>
}
<tr>
<td>
<input type="submit" class="btn btn-default" />
</td>
</tr>
</table>
</form>
Model (Device.cs)
public class Device
{
public int Id { get; set; }
public string Name { get; set; }
public bool CheckState { get; set; }
}
Model (Data.cs, the Device objects get initialized here)
private static List<Device> devices = new List<Device>();
static Data()
{
devices.Add(new Device() { Id = 1, Name = "Laptop" });
devices.Add(new Device() { Id = 2, Name = "Tablet" });
devices.Add(new Device() { Id = 3, Name = "Apple Watch" });
}
public static List<Device> GetDevices()
{
return devices;
}
Controller (RegisterController.cs)
public class RegisterController : Controller
{
// GET: /<controller>/
[HttpGet]
public IActionResult Index()
{
PMRegistration pm = new PMRegistration();
pm.Devices = Data.GetDevices();
return View(pm);
}
public ActionResult Create(PMRegistration pm)
{
if (ModelState.IsValid)
{
return View("Overview", pm);
}
else
{
return RedirectToAction("Index");
}
}
}
------------ SOLVED -------------
With HTML-helpers:
#for (int i = 0; i < Model.Devices.Count; i++)
{
<tr>
<td>
#Model.Devices[i].Name
</td>
<td>
#Html.CheckBoxFor(m => Model.Devices[i].CheckState)
#Html.HiddenFor(m => Model.Devices[i].Id)
#Html.HiddenFor(m => Model.Devices[i].Name)
</td>
</tr>
}

Should I use ViewBag to pass a list to a View?

Not sure why I got down voted but I'm going to re-write my question after doing some research and testing. This is a side project that I'm using to learn MVC/EF/Repository/Bootstrap etc. I only get a couple hours here a few nights a week to work on it.
Basic original question:
I know I should really be using a List<> in a ViewModel to pass the data to the View but I'm not sure how or if it will meet my requirement.
What I am trying to do is get a list of users to display in a table which would have a checkbox in each row. Above that table I want to have a list of Groups to that they could be assigned to. You select the section from the DropDownList (DDL) and then check who you want to assign it to. It's the groups/sections that I want want to assign as a list and pass to the View.
So, I've got a ViewModel with a list and I'm using a repository to populate the VM. What I don't know how to do exactly is where/when to populate that list with each VM object and even if I do and there are say 50 users I wouldn't want to make 50 trips to the DB to pull the same information.That is why I'm thinking that for this scenario using the ViewBag to pass that Group list to the View might be justifiable. On the flip side I would like to learn how to populate that list properly in the VM for future coding.
Updated question/code:
So, after more research and following some suggestions I've now got the following code. I'm still not sure how I will properly populate my Patrols in my ViewModel in order to populate the DDL in my View.
At the moment I've got the View displaying the table with the checkboxes. Now I'm back to working on getting the values to populate the DDL and then I'll have to work on posting to the controller, looping to find the check rows, and updating the database. In my case each member record is defaulted to a PatrolId=0 and this page should allow me to update the PatrolId to a value from the DDL.
The Patrols property in the PatrolMemberViewModel should be a list of about 5 records that I would pull from a DB table instead of hard coding in the DDL.
ViewModel:
public class PatrolViewModel
{
public int PatrolId { get; set; }
public string PatrolName { get; set; }
}
public class PatrolMemberViewModel
{
[Key]
public int MemberId { get; set; }
public int PatrolId { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone")]
public string PhonePrimary { get; set; }
[Display(Name = "Email")]
public string EmailPrimary { get; set; }
public bool IsSelected { get; set; }
public PatrolViewModel Patrols { get; set; }
}
Controller:
public ViewResult Unassigned()
{
try
{
IEnumerable<PatrolMemberViewModel> model = repository.SelectAllUnassigned();
return View(model);
}
catch (Exception)
{
ModelState.AddModelError(string.Empty, "Error retrieving the record.");
return View();
}
}
Repository:
public IEnumerable<PatrolMemberViewModel> SelectAllUnassigned()
{
using (DataContext db = new DataContext())
{
var results = (from p in db.Person
where p.IsActive == true
&& p.IsScout == true
&& p.PatrolId == 0
select new PatrolMemberViewModel
{
MemberId = p.PID,
FirstName = p.FirstName ?? string.Empty,
LastName = p.LastName ?? string.Empty,
EmailPrimary = p.EmailPrimary ?? string.Empty,
PhonePrimary = p.PhonePrimary ?? string.Empty,
PatrolId = p.PatrolId,
IsSelected = false
}
).OrderBy(o => o.LastName).ThenBy(o => o.FirstName).ToList();
return results;
}
}
View:
#model IList<ProjectName.ViewModels.PatrolMemberViewModel>
#{
ViewBag.Title = "Unassigned";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Patrols</h2>
#using (Html.BeginForm("Update", "Patrol", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "alert alert-danger" })
<table class="table table-bordered table-striped table-hover table-condensed tbackground">
<tr>
<th class="text-center">
</th>
<th class="text-center">
First Name
</th>
<th class="text-center">
Last Name
</th>
<th class="text-center">
Email
</th>
<th class="text-center">
Phone
</th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td class="text-center">
#Html.CheckBoxFor(m => m[i].IsSelected)
</td>
<td>
#Html.DisplayFor(m => m[i].FirstName)
</td>
<td>
#Html.DisplayFor(m => m[i].LastName)
</td>
<td>
#Model[i].EmailPrimary
</td>
<td class="text-center">
#Html.DisplayFor(m => m[i].PhonePrimary)
</td>
</tr>
}
</table>
<div class="control-wrapper">
<input type="submit" id="btnSubmit" value="Assign" class="btn btn-success" />
</div>
}
<p> </p>
Start by creating the view models to represent what you want to display/edit in the view. Your PatrolMemberViewModel can be used but remove the [Key] attribute and the int PatrolId and PatrolViewModel Patrols properties.
Then create the parent view model
public class AssignPatrolViewModel
{
[Display(Name = "Patrol")]
[Required(ErrorMessage = "Please select a patrol")]
public int? SelectedPatrol { get; set; }
public IEnumerable<SelectListItem> PatrolList { get; set; }
public List<PatrolMemberViewModel> Members { get; set; }
}
and you GET method would be
public ViewResult Unassigned()
{
var model = new AssignPatrolViewModel
{
PatrolList = new SelectList(db.Patrols, "PatrolId", "PatrolName"), // modify to suit
Members = repository.SelectAllUnassigned().ToList()
};
return View(model);
}
and in the view
#model AssignPatrolViewModel
....
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.SelectedPatrol)
#Html.DropDownListFor(m => m.SelectedPatrol, Model.PatrolList, "Please select")
#Html.ValidationMessageFor(m => m.SelectedPatrol)
<table>
.... // thead elements
<tbody>
#for(int i = 0; i < Model.Members.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(m => m.Members[i].IsSelected)
#Html.HiddenFor(m => m.Members[i].MemberId)
// add other hidden inputs for properties you want to post
</td>
<td>#Html.DisplayFor(m => m.Members[i].FirstName)</td>
....
</tr>
}
</tbody>
</table>
<input type="submit" value="Assign" class="btn btn-success" />
}
Then in the POST method
[HttpPost]
public ViewResult Unassigned(AssignPatrolViewModel model)
{
if (!ModelState.IsValid)
{
model.PatrolList = new SelectList(db.Patrols, "PatrolId", "PatrolName");
return View(model);
}
// Get selected ID's
IEnumerable<int> selected = model.Members.Where(m => m.IsSelected).Select(m => m.MemberId);
// Get matching data models
var members = db.Person.Where(p => selected.Contains(p.PID)); // modify to suit
// loop each each member, update its PatrolId to the value of model.SelectedPatrol
// save and redirect
}
You could create a new class for your view model, with the list of users and the list of sections as properties within it. Some people seem to like that approach.
But I think your use of ViewBag for passing the list of sections is perfectly valid. I do that all the time for DDLs like this.

I can not get the value of a textbox in my controller MVC

* Hello i have long time trying it and i dont get any results, my problem is the next:
On my controller i can not get the value of the textbox, but if I put the form and the textbox out of the loop i get the value.*
** this is my view:**
#for (int r = 0; r <= Model.Count-1;r++)
{
i = i + 1;
<tr>
#using (Html.BeginForm("Result","Ruta", new { ruta=Model [r].descrip ,ficha =Model [r].ficha }, FormMethod.Post))
{
if (i == 1)
{
#Html.TextBox("FechaInicio")
}
<td>
#Html.DisplayFor(modelItem => Model[r].ruta)
</td>
<td>
#Html.DisplayFor(modelItem => Model[r].descrip)
</td>
<td>
#Html.DisplayFor(modelItem => Model[r].ficha)
</td>
<td>
<input type="Submit" value="Consultar" style=" height :20px; font-size:12px; "/>
</td>
}
</tr>
My Controller:
[HttpPost]
public ActionResult Result(string ficha, string ruta)
{
Utility.Fecha1 = Request.Form ["FechaInicio"];
if (string.IsNullOrEmpty(ficha) || string.IsNullOrEmpty(ruta) || string .IsNullOrEmpty ( Utility .Fecha1) )
{
return RedirectToAction("FichaConduces", "Ruta", new { ficha = ficha, ruta = ruta,fecha=Utility .Fecha1 });
}
else
{
return View("index");
}
}
Why don't you do the simple way?
Create a view based on view model,
and create textboxs for view model's field in view then you can easily get values you want from the form.
And, when you create textbox it should be #Html.TextBoxFor(....)
For example
ViewModel
public class MyViewModel
{
public string MyField1{get; set;}
public string MyField2{get; set;}
}
Then in controller's HttpGet
[HttpGet]
public ActionResult MyControllerAction()
{
var myViewModel = new MyViewModel();
return View(myViewModel);
}
in view
#model MyViewModel
#using(Html.BeginForm("Action","Controller",FormMethod.Post))
{
#Html.TextBoxFor(m=>m.MyField1)
....
}
controller's HttpPost
[HttpPost]
public ActionResult MyControllerAction(MyViewModel myViewModel)
{
//do whatever you want
}

Using Jquery to append rows in MVC

I have a dynamically generated gridview which is made of table and textbox controls and an add and remove button.
The add button calls a jquery function which adds new row at the bottom of the grid and the remove button removes a particular row.
Problem:
Assuming I have 5 rows from the database and I add a new row and perform a count to check the number of textboxs I discover that it count only newly added textbox.
View:
#{
for (var i = 0; i < Model.Image_Count; i++ )
{
<tbody id="image-row">
<tr>
<td class="left">
<table>
<tr>
<td>
<img class="img-tag" id="img-row-tag" src="#Model.Product_ImageLink[i]" alt="no-image" />
#Html.HiddenFor(x => x.Product_ImageLink[i])
</td>
</tr>
<tr>
<td>
<a id="lnk" onclick="_file_upload(this);" class="button">Upload File</a>
<input id="file_row" class="file-tag" onchange="readURL_(this, i);" type="file" name="file_row" />
<div class="validation-area">
#Html.ValidationMessageFor(x => x.Product_ImageLink[i])
</div>
</td>
</tr>
</table>
</td>
<td class="right">
#Html.TextBoxFor(x => x.Product_SortOrder[i])
</td>
<td class="left"><a onclick="$('#image-row' + i).remove();" class="button">-</a></td>
</tr>
</tbody>
}
}
JQuery:
var attribute_row = 1;
function addattribute(){
html = '<tbody id="attribute-row' + attribute_row + '">';
html += ' <tr>';
html += ' <td class="left">#Html.TextBoxFor(x=>x.AttributeName)<div class="validation-area">#Html.ValidationMessageFor(x => x.AttributeName)</div></td>';
html += ' <td class="right"><input type="text" name="Attribute_SortOrder" id="Attribute_SortOrder"></td>';
html += ' <td class="left"><a onclick="$(\'#attribute-row' + attribute_row + '\').remove();" class="button">-</a></td>';html += ' </tr>';
html += '</tbody>';$('#attribute tfoot').before(html);
attribute_row++;$('#Attribute_Count').val(attribute_row);
}
Model:
public bool[] IsDefault { get; set; }
public string Image_Link { get; set; }
public string Image_Path { get; set; }
public string[] Product_ImageLink { get; set; }
public int[] Product_SortOrder { get; set; }
public int Image_Count { get; set; }
public int iCount { get; set; }
Controller:
public ActionResult Products(int? id)
{
if (id == null)
{
}
else
{
var y = _repository.GetProductImage(id);
List<string> _Product_ImageLink = new List<string>();
List<int> _Product_SortOrder = new List<int>();
foreach (var z in y)
{
_Product_ImageLink.Add(z.Product_ImageLink);
_Product_SortOrder.Add(z.Product_SortOrder);
}
model.Product_SortOrder = _Product_SortOrder.ToArray();
model.Product_ImageLink = _Product_ImageLink.ToArray();
}
return View(model);
}
[HttpPost]
public ActionResult Products(ProductModel _model, int? id)
{
if (ModelState.IsValid)
{
if (_model.ProductId == 0)
{
}
else
{
int jCount = _model.Product_ImageLink.Count();
}
}
else
{
_Message("Error", "Please check the form carefully for errors!");
}
ViewBag.IsButtonClick = true;
return View(_model);
}
What you can do is maybe initialize your javascript variable with Razor:
var attribute_row = #Model.Image.Count();
Hope it'll help you!
Sebastien

How to deal with many possible values to make a query?

I'm building an MVC app in which the user will have the possibilities of using a lot of filters to get exactly what he wants.
Here's an overview of those filters based on the controller method:
//
// GET: /Card/SearchIndex
public ActionResult SearchIndex(string objName, string objType, string objCostSymbol, string objCost, string powerSymbol,
string powerValue, string ratingSymbol, string ratingValue, string ownerName, string objSet,
string objRarity, string addCostValue, int? objNumber,
string addCostValue2, string addCostValue3, string addCostValue4, string addCostValue5, string addCostValue6,
bool? blueColor, bool? redColor, bool? yellowColor, bool? purpleColor, bool? greyColor, bool? blackColor,
bool? musicColor, bool? allColor)
{
// MORE CODE HERE...
}
I want to know how would be the best way to deal with all these filters, and how could I get a List of objInfo based on the given parameters. Keep in mind that some values may be null. All I've done up to now is load "all" the objInfo I could, then sort them by removing the non-wanted item, which is in my sense "not smart", but I'm new to MVC App and I'm trying to find a better way to do this.
EDIT
Here's the view that generates the data:
#using System.Web.Mvc.Html
#model PagedList.IPagedList<MvcApp.Models.ObjInfo>
#{
ViewBag.Title = "SearchIndex";
}
<h2>Objects Management</h2>
<p>
#Html.ActionLink("Create New Obj", "Create")
#using (Html.BeginForm()){
<p>
<label>
Obj Colors : Check a box to search for a color.
</label>
All: #Html.CheckBox("allColor", true)<br/>
Blue: #Html.CheckBox("blueColor", true)
Red: #Html.CheckBox("redColor", true)
Yellow: #Html.CheckBox("yellowColor", true) <br/>
Purple: #Html.CheckBox("purpleColor", true)
Grey: #Html.CheckBox("greyColor", true)
Black: #Html.CheckBox("blackColor", true)
Music: #Html.CheckBox("musicColor", true)
</p>
<p>
<label>
Obj Values: Select a value in the list below.
</label>
Obj Number: <input type="number" min="0" max="9999" name="cardNumber" value="int" style="width: 70px"/><br/>
Additional Cost (contains): #Html.DropDownList("addCost", String.Empty) + #Html.DropDownList("addCost2", String.Empty)
+ #Html.DropDownList("addCost3", String.Empty) + #Html.DropDownList("addCost4", String.Empty)
+ #Html.DropDownList("addCost5", String.Empty) + #Html.DropDownList("addCost6", String.Empty) <br/>
Cost: #Html.DropDownList("objCostSymbol", "=") #Html.DropDownList("objCost", String.Empty)<br />
Power: #Html.DropDownList("powerSymbol", "=") #Html.DropDownList("powerValue", String.Empty)<br/>
Rating: #Html.DropDownList("ratingSymbol", "=") #Html.DropDownList("ratingValue", String.Empty)<br />
<label>
Obj Text: Write a name, part of a name, or a word.
</label>
Obj Name: #Html.TextBox("objName") <br/>
Owner: #Html.TextBox("ownerName") <br />
<label>
Obj Categories: Select a category in the list below.
</label>
Type: #Html.DropDownList("objType","All") <br/>
Obj Set: #Html.DropDownList("objSet", "All") <br/>
Rarity: #Html.DropDownList("objRarity", "All")<br />
<div class="float-right">
<input type="submit" value="Filter" name="submitbutton">
</div>
</p>
}
</p>
<span style="color:red; font-size: 1.7em; font-style: italic;">#ViewData["ErrorMessage"]</span>
<table>
<tr>
<th>Obj Name</th>
<th>Obj Number</th>
<th>Obj Color</th>
<th>Additional Cost</th>
<th>Cost</th>
<th>Obj Type</th>
<th>#Html.ActionLink("Power", "SearchIndex", new {sortOrder=ViewBag.PowerSortParm})</th>
<th>#Html.ActionLink("Rating", "SearchIndex", new {sortOrder=ViewBag.RatingSortParm})</th>
<th>Rarity</th>
<th>Obj Set Name</th>
<th>Owner Name</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.m_ObjName)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjColor)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjAddCost)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjCost)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjType)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjPower)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjRating)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjRarity)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjSet.m_ObjSetName)
</td>
<td>
#Html.DisplayFor(modelItem => item.m_ObjOwner)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.m_ObjID }) |
#Html.ActionLink("Details", "Details", new { id=item.m_ObjID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.m_ObjID })
</td>
</tr>
}
</table>
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "SearchIndex", new {page = 1, sortOrder = ViewBag.CurrentSort})
#Html.Raw(" ")
#Html.ActionLink("< Prev", "SearchIndex", new {page = Model.PageNumber - 1, sortOrder = ViewBag.CurrentSort})
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next >", "SearchIndex", new {page = Model.PageNumber + 1, sortOrder = ViewBag.CurrentSort})
#Html.Raw(" ")
#Html.ActionLink(">>", "SearchIndex", new {page = Model.PageCount, sortOrder = ViewBag.CurrentSort})
}
else
{
#:Next >
#Html.Raw(" ")
#:>>
}
</div>
Any advice will help me do a better job, thank you.
Ho do you normally face this in JavaScript ? You would create an option object, like
var op = {
cardName : "..",
cardType : "" ,
...
}
and pass it to a function. Correct ?
The same do in C# too.
Define a, say, Conditions class, like
public class Conditions {
public string CardName {get;set;}
public string CardType {get;set;}
..
}
and pass it to your function, which controls the values of the properties of that type to act accordingly after.
Why do you not use ModelBinder . I think it's very useful with your case. Please see below:
_ I have a Model:
public class Employee
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public Address HomeAddress { get; set; }
}
and ModelBinder for Employee:
public class EmployeeBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
var emp = new Employee {
Id = controllerContext.HttpContext.Request.Form["Id"],
FirstName = controllerContext.HttpContext.Request.Form["FirstName"],
LastName = controllerContext.HttpContext.Request.Form["LastName"],
BirthDate = new DateTime(int.Parse(controllerContext.HttpContext.Request.Form["year"]),
int.Parse(controllerContext.HttpContext.Request.Form["month"]),
int.Parse(controllerContext.HttpContext.Request.Form["day"]))
};
return emp;
}
}
Then Controller:
public ActionResult Example(Employee emp) {
return View(emp);
}
URL: http://localhost:1034/Home/Example?Id=1&LastName=lazycatit
Here's a way you could handle your problem.
First, create a ViewModel with your search parameters.
public class FilterViewModel
{
public string ObjName { get; set; }
public string ObjType { get; set; }
public string OtherType { get; set; }
}
In your controller, pass this to the view.
public virtual ActionResult SearchResults()
{
return View(new FilterViewModel());
}
In your SearchResults.cshtml you need to encode the model to a json and then use an ajax call to filter your results. Assumming there's a button with btnFilterResults id. This is going to load the results from a partial view (that should be your table) using ajax.
<script type="text/javascript">
var dataViewModel = #Html.Raw(Json.Encode(Model));
$("#btnFilterResults").click(function () {
dataViewModel.ObjName = $("#objName").val(); //Make sure the ids corresponde to your html.
dataViewModel.ObjType = $("#objType").val();
dataViewModel.OtherType = $("#otherType").val();
$.ajax({
url: "#Url.Action(MVC.ControllerName.GetSearchResults())",
data: { viewModel: JSON.stringify(dataViewModel) },
success: function(data) {
$("#tableDiv").empty(); //
$("#tableDiv").html(data);
}
});
});
</script>
Finally, in your controller you can get the results:
[HttpGet]
public virtual ActionResult LoadTableReporteGeneral(string viewModel)
{
var filterOptions = JsonConvert.DeserializeObject<FilterViewModel>(viewModel);
var query = from t in db.YourTableName
select t;
//This returns an IQueryable with all of your data, no filtering yet.
//Start filtering.
if(!String.IsNullOrEmpty(filterOptions.ObjName))
{
query = query.Where(x => x.ObjName == filterOptions.ObjName);
}
if(!String.IsNullOrEmpty(filterOptions.ObjType ))
{
query = query.Where(x => x.ObjType == filterOptions.ObjType );
}
//and so on.
//Finally return a partial view with your table.
return PartialView(MVC.Shared.Views._YourTableName, query);
}
Note: I'm using T4MVC and Json.Net packages.
Hope this helps.

Categories