I have a model called Result. Suppose this has 4 fields, like student_id, marks, status, remarks.
Now I have a view in which student listing is shown. In front of each student, there is a button for enter marks of exam. On clicking on button a pop-up will open and there will be 2 fields student_id, marks and 2 buttons 'pass' and 'fail'.
On clicking on fail button another pop-up will appear for enter remarks only.
Now my question is that, how can I retain values of first pop-up on second pop-up, As on clicking on 'submit' button of second pop-up, I will save all the details.
I know a way to do this using hidden fields in second pop-up. Is there any other way to do this?
Model classes are:
1. User (id, name, f_name, address...)
2. Result (student_id, marks, grade, remarks)
Student List view
#{
List<User> Student = (List<User>)ViewData["Student"];
}
<table id="table_id">
<tr>
<th class="dbtc">S.No.</th>
<th class="dbtc">Student Name)</th>
<th style="width: 110px">Operate</th>
</tr>
#foreach (User usr in Student)
{
int index = Student.IndexOf(usr);
<tr>
<td class="dbtc">
#(Student.ToList().IndexOf(usr) + 1)
</td>
<td>
#Html.ActionLink(usr.FirstName + " " + usr.LastName, "Details", "User", new { id = usr.Id }, null)
</td>
<td>
#Ajax.ActionLink("Examine", "Result", new { id = Model.Id, userId = usr.Id }, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "divPopup",
InsertionMode = InsertionMode.Replace,
OnSuccess = "openPopup('Examine Content')"
})
</td>
</tr>
First Partial view of examine
#model ComiValve.Models.Result
#using (Html.BeginForm("ExamPass", "Student", new { #id = (int)ViewBag.id, userId = (int)ViewData["UserId"] }, FormMethod.Post))
{
<div id="divExamAdvice"></div>
<div class="editor-label">
#Html.DisplayNameFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Marks)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Grade)
</div>
<div class="login_submit_div">
<input type="submit" value="Pass" />
#Ajax.ActionLink("Fail", "ExamAdvice", new { id = (int)ViewBag.id, userId = (int)ViewData["UserId"] }, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "divPopup",
OnSuccess = "openPopup('Exam Advice')"
})
</div>
}
Second partial view for remaks (when user click on fail, then this view will open.)
#model ComiValve.Models.ExamContent
#using (Html.BeginForm("ExamFail", "Student", new { id = Model.id }, FormMethod.Post))
{
<div id="divExamAdvice"></div>
<div class="editor-label">
#Html.DisplayNameFor(model => model.Remarks)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.Remarks)
</div>
<div class="left">
<input type="submit" value="Confirm Fail" />
</div>
}
Methods of Controller
public virtual ActionResult ExamContent(int id, int userId)
{
ViewBag.IsApprove = true;
ViewBag.UserId = userId;
ViewBag.id = id;
return PartialView("ExamContent");
}
public virtual ActionResult ExamAdvice(int id, int userId)
{
ViewBag.IsApprove = true;
if (Request.IsAjaxRequest())
{
Result result = new Result();
result.id = id;
result.User = db.Users.Find(userId);
return PartialView("ExamAdvice", result);
}
else
{
return RedirectToAction("Index");
}
}
Why are you passing the model between partial views. You can create a single Model and use it on both the views. In case of having two different tables, create the two different "Lists" of "Table" type. Like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Web.Mvc;
namespace LearningMVCapp.Models
{
public class Data
{
public List<tbl_Dept> lstDepatrment;
public List<tbl_employees> lstEmployees;
//other properties
}
}
You can also use session instead of hidden fields, refer this link http://www.dotnet-tricks.com/Tutorial/mvc/906b060113-Controlling-Session-Behavior-in-Asp.Net-MVC4.html.
Related
I am having an issue trying to return to my index (List) page with my filter set correctly. The filter is never set on return from the details page and always defaults to the first value in the drop down list. Using the Html helper EnumDropDownListFor.
EDIT: I should point out that if I change the current month filter from the index page that it posts correctly to the Index ActionResult and the filter is correctly set back in the Index page. So the issue is when posting from the details page back to the Index page only.
Here's my code.
Model Code:
using System;
using System.Collections.Generic;
namespace ShiftPatternConfigurator.Models
{
// shift view
public class ShiftViewModel
{
public IEnumerable<Shift> Shifts { get; set; }
public Month Month { get; set; }
}
// shift model
public class Shift
{
public int ShiftNo;
public string ShiftName;
public DateTime StartTime;
public DateTime FinishTime;
public string Team;
public int Week;
public int CycleWeek = 0;
public string StartDay;
public DateTime StartDate;
}
// month enum
public enum Month
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12
}
}
Controller Code:
using ShiftPatternConfigurator.DataAccess;
using ShiftPatternConfigurator.Models;
using System;
using System.Web.Mvc;
namespace ShiftPatternConfigurator.Controllers
{
public class HomeController : Controller
{
// GET: Index
public ActionResult Index()
{
ViewBag.Title = "Shift Pattern";
ShiftViewModel monthShiftView = new ShiftViewModel
{
Month = new Month()
};
monthShiftView.Month = (Month)DateTime.Now.Month;
monthShiftView.Shifts = DbContext.GetShiftsByMonth(monthShiftView.Month);
return View(monthShiftView);
}
// POST: Index
[HttpPost]
public ActionResult Index(Month month)
{
ViewBag.Title = "Shift Pattern";
ShiftViewModel monthShiftView = new ShiftViewModel
{
Month = new Month()
};
monthShiftView.Month = month;
monthShiftView.Shifts = DbContext.GetShiftsByMonth(monthShiftView.Month);
return View(monthShiftView);
}
// GET: Details
public ActionResult Details(int shiftNo, Month monthFilter)
{
ViewBag.Title = "Shift Details";
ViewBag.MonthFilter = monthFilter;
Shift shift = DbContext.GetShiftByShiftNo(shiftNo);
return View(shift);
}
}
}
Index (List) Code:
#model ShiftPatternConfigurator.Models.ShiftViewModel
<div class="jumbotron">
<h1>#ViewBag.Title - #Model.Month</h1>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.EnumDropDownListFor(x => x.Month)
<input type="submit" value="Select Month" class="btn btn-primary btn-sm" />
}
</div>
<table class="table">
<tr>
<th>Shift No</th>
<th>Shift Name</th>
<th>Start Time</th>
<th>Finish Time</th>
<th>Team</th>
<th>Week</th>
<th>Start Day</th>
<th>Start Date</th>
<th></th>
</tr>
#if (Model.Shifts.Count() > 0)
{
foreach (var item in Model.Shifts)
{
<tr>
<td>#item.ShiftNo</td>
<td>#item.ShiftName</td>
<td>#item.StartTime</td>
<td>#item.FinishTime</td>
<td>#item.Team</td>
<td>#item.Week</td>
<td>#item.StartDay</td>
<td>#item.StartDate.ToShortDateString()</td>
<td>
<div class="btn-group btn-group-xs">
#Html.ActionLink("Edit", "Edit", new { shiftNo = item.ShiftNo, monthFilter = Model.Month }, new { #class = "btn btn-primary" })
#Html.ActionLink("Details", "Details", new { shiftNo = item.ShiftNo, monthFilter = Model.Month }, new { #class = "btn btn-primary" })
</div>
</td>
</tr>
}
}
else
{
<tr>
<td colspan="10" align="center"><h2>No Data</h2></td>
</tr>
}
</table>
Detail Code:
#using ShiftPatternConfigurator.Models
#model Shift
<h2>#ViewBag.Title</h2>
<div>
<h4>Shift - #Model.ShiftNo</h4>
<hr />
<dl class="dl-horizontal">
<dt>Shift No:</dt>
<dd>#Model.ShiftNo</dd>
<dt>Shift Name</dt>
<dd>#Model.ShiftName</dd>
<dt>Start Time</dt>
<dd>#Model.StartTime.ToShortDateString() #Model.StartTime.ToLongTimeString()</dd>
<dt>Finish Time</dt>
<dd>#Model.FinishTime.ToShortDateString() #Model.FinishTime.ToLongTimeString()</dd>
<dt>Team:</dt>
<dd>#Model.Team</dd>
<dt>Week:</dt>
<dd>#Model.Week</dd>
<dt>Cycle Week:</dt>
<dd>#Model.CycleWeek</dd>
<dt>Start Day:</dt>
<dd>#Model.StartDay</dd>
<dt>Start Date:</dt>
<dd>#Model.StartDate</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
#Html.ActionLink("Back to List-ActionLink", "Index", "Home", new { month = ViewBag.MonthFilter })
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.Hidden("month", (Month)ViewBag.MonthFilter)
<input type="submit" value="Back to List-Form" class="btn btn-primary btn-sm" />
}
#Ajax.ActionLink("Back to List-Ajax", "Index", "Home",
new { month = (Month)ViewBag.MonthFilter },
new AjaxOptions { HttpMethod = "POST" },
new { #class = "btn btn-primary btn-sm" })
</p>
I have tried the following ways to get back to my index page with the filter set:
#Html.ActionLink method
I have found that this will not work as ActionLink always sends a GET request so I cannot use this method.
#Html.ActionLink("Back to List-ActionLink", "Index", "Home", new { month = ViewBag.MonthFilter })
#Ajax.ActionLink method
Using the Ajax method the Index POST method gets hit but the page stays on the detail page.
#Ajax.ActionLink("Back to List-Ajax", "Index", "Home",
new { month = (Month)ViewBag.MonthFilter },
//new AjaxOptions { HttpMethod = "POST", OnSuccess = "window.location.href = '/'" },
new AjaxOptions { HttpMethod = "POST" },
new { #class = "btn btn-primary btn-sm" })
#Html.BeginForm method
With this method it posts correctly to the POST ActionResult correctly, however the drop down list defaults to the first in the list. So the filter is not passed correctly to the enumdropdownlistfor.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.Hidden("month", (Month)ViewBag.MonthFilter)
<input type="submit" value="Back to List-Form" class="btn btn-primary btn-sm" />
}
Here is method 3 using #Html.BeginForm to post back, in screenshots with debugging values shown:
Page is launched and hits the GET index ActionResult, the Models Month enum is set to the current month and the list of shifts are returned from the BDcontext and assigned to the Model.
The Index view then renders the Html setting the EnumDropDownListFor to the currect date correctly
As you can see from the image the month is set to the current month.
EDIT: Here is the correctly generated HTML output by the #Html.EnumDropDownListFor helper
After Selecting the details link, the code hits the GET details ActionResult and renders the view correctly.
After hitting the back to List-Form button the POST Index Action Result is hit correctly setting all the parameters.
But the view is rendered with the Month filter defaulting to the first in the list, not my selected month.
EDIT: Here is the incorrectly generated HTML output by the #Html.EnumDropDownListFor helper
Please help with suggestions how I can make this work.
So I found a work around for my issue, although it feels like it is a hack opposed to the correct way to do it. Maybe someone can comment as to why it didn't work the way I wanted it to?
What I did was the following:
Use ActionLink in my Detail page passing a parameter.
Handle the optional parameter in my GET Index ActionResult method.
So the code looks like this.
Detail View Action Link:
#Html.ActionLink("Back to List", "Index", "Home", new { monthFilter = ViewBag.MonthFilter }, new { #class = "btn btn-primary btn-sm" })
Index (List) GET ActionResult:
// GET: Index
public ActionResult Index(string monthFilter)
{
ViewBag.Title = "Shift Pattern";
ShiftViewModel monthShiftView = new ShiftViewModel
{
Month = new Month()
};
// hack to fix issue with filter not being passed back to index page from Details view
if(monthFilter == null)
monthShiftView.Month = (Month)DateTime.Now.Month;
else
monthShiftView.Month = (Month)Enum.Parse(typeof(Month), monthFilter); ;
monthShiftView.Shifts = DbContext.GetShiftsByMonth(monthShiftView.Month);
return View(monthShiftView);
}
So as you can see I handle the month value, by using the current month if the month value passed in is null or I use the value passed in if its available to be used.
I have numerous data displayed in a table, let's say a long list of users (first name & last name), so I set up a paging feature to display the elements by pages via the PagedList NuGet package. I was inspired by this tutorial: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
I implemented a drop-down list in my view, so that I can directly choose the number of elements to display per page. I managed to include a jQuery script that makes the page size update whenever the drop-down list has a new selected value.
Using the mentioned tutorial , I also added a search feature: submitting a string in a search form allows to filter the data.
My problem is: changing the page size by selecting a new value in the drop-down list after having done a search doesn't work: the search results are reset, all the entries being displayed instead. I guess I forgot to pass some parameter somewhere but I just can't figure out where...
Here is my controller:
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
// Sort order is passed to view in order to keep it intact while clicking in another page link
ViewBag.CurrentSort = sortOrder;
// Ascending or descending sorting by first or last name according to sortOrder value
ViewBag.LastNameSortParm = String.IsNullOrEmpty(sortOrder) ? "lastname_desc" : "";
ViewBag.FirstNameSortParm = sortOrder == "firstname" ? "firstname_desc" : "firstname";
// Not sure here
if (searchString == null)
{
searchString = currentFilter;
}
// Pass filtering string to view in order to maintain filtering when paging
ViewBag.CurrentFilter = searchString;
var users = from u in _db.USER select u;
// FILTERING
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(u => u.lastname.Contains(searchString)
|| u.firstname.Contains(searchString)
}
// Ascending or descending filtering by first/last name
switch (sortOrder)
{
case "lastname": // Ascending last name
users = users.OrderBy(u => u.lastname);
break;
case "lastname_desc": // Descending last name
users = users.OrderByDescending(u => u.lastname);
break;
case "firstname": // Ascending first name
users = users.OrderBy(u => u.firstname);
break;
case "firstname_desc": // Descending first name
users = users.OrderByDescending(u => u.firstname);
break;
default:
users = users.OrderBy(u => u.lastname);
break;
}
// DROPDOWNLIST FOR UPDATING PAGE SIZE
int count = _db.USER.OrderBy(e => e.Id).Count(); // Total number of elements
// Populate DropDownList
ViewBag.PageSize = new List<SelectListItem>() {
new SelectListItem { Text = "10", Value = "10", Selected = true },
new SelectListItem { Text = "25", Value = "25" },
new SelectListItem { Text = "50", Value = "50" },
new SelectListItem { Text = "100", Value = "100" },
new SelectListItem { Text = "All", Value = count.ToString() }
};
int pageNumber = (page ?? 1);
int pageSize = (PageSize ?? 10);
ViewBag.psize = pageSize;
return View(users.ToPagedList(pageNumber, pageSize));
}
And my Index.cshtml view:
<script src="~/Scripts/jquery-3.2.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { // Submit pageSizeForm when another pageSize value is selected
$("#pageSize").change(function () {
$("#pageSizeForm").submit();
});
});
</script>
#model PagedList.IPagedList<AfpaSIPAdmin.Models.USER>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Users management";
}
<h1>Users management</h1>
<!-- Creating a new entry in table -->
<p>
#Html.ActionLink("Create new user", "Create")
</p>
<!-- Filtering table entries -->
#using (Html.BeginForm("Index", "Users", FormMethod.Get, new { id = "filterForm" }))
{
<p>
Filter: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string, new { #placeholder = "First or last name..." })
<input type="submit" value="Apply"/>
</p>
}
<!-- Display table -->
<table class="table">
<tr>
<th>
#Html.ActionLink("Last name", "Index", new {
sortOrder = ViewBag.LastNameSortParm,
currentFilter = ViewBag.CurrentFilter
})
</th>
<th>
#Html.ActionLink("First name", "Index", new {
sortOrder = ViewBag.FirstNameSortParm,
currentFilter = ViewBag.CurrentFilter
})
</th>
<th style="min-width: 170px"></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td style = "min-width: 150px">
#Html.DisplayFor(modelItem => item.lastname)
</td>
<td style = "min-width: 150px">
#Html.DisplayFor(modelItem => item.firstname)
</td>
<td> <!-- Using images as buttons for actions -->
<a href="#Url.Action("Edit", "Users", new { id = item.Id })" title="Edit">
<img src="~/Content/images/edit.gif" />
</a>
<a href="#Url.Action("Details", "Users", new { id = item.Id })" title="Details">
<img src="~/Content/images/info.gif" />
</a>
<a href="#Url.Action("Delete", "Users", new { id = item.Id })" title="Delete">
<img src="~/Content/images/delete.gif" />
</a>
</td>
</tr>
}
</table>
<br/>
<!-- Paging -->
#using (Html.BeginForm("Index", "Users", FormMethod.Get, new { id = "pageSizeForm" }))
{
<div class="pager">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) sur #Model.PageCount<br/>
#Model.Count of #Model.TotalItemCount elements
#Html.PagedListPager(Model, page => Url.Action("Index", new {
page,
sortOrder = ViewBag.CurrentSort,
currentFilter = ViewBag.CurrentFilter,
searchString = ViewBag.CurrentFilter,
pageSize = ViewBag.psize
}))
<!-- DropDownList for setting page size -->
Elements per page :
#Html.DropDownList("pageSize")
</div>
}
The reason is because you have 2 forms. When you submit the first form containing the textbox, the only value you send back to the controller is SearchString and all the other parameters in your method will be their default (for example when you return the view, PageSize will default to null and therefore return only 10 records even if the user previously selected say 50.
Likewise, when you submit the 2nd form containing dropdownlist for the page size, the value of SearchString will be null because its not sent in the request.
You need to have one form only containing both form controls. And if you wanted to send additional properties, for example the current sort order, then you can add those as query string values in the form element (for example, #using(Html.BeginForm("Index", "Users", new { sortOrder = .... }, FormMethod.Get))
I would also strongly recommend you use a view model containing the properties you need in the view and strongly bind to them rather than using ViewBag
public class UsersVM
{
public string SearchString { get; set; }
public int PageSize { get; set; }
public IEnumerable<SelectListItem> PageSizeOptions { get; set; }
.....
public IPagedList<USER> Users { get; set; }
}
View
#model UsersVM
...
#using(Html.BeginForm("Index", "Users", FormMethod.Get))
{
#Html.LabelFor(m => m.SearchString)
#Html.TextBoxFor(m => m.SearchString)
#Html.LabelFor(m => m.PageSize)
#Html.DropDownListFor(m => m.PageSize, Model.PageSizeOptions)
<input type="submit" value="Filter" />
}
....
<div class="pager">
Page #(Model.Users.PageCount < Model.Users.PageNumber ? 0 : Model.Users.PageNumber)
....
#Html.PagedListPager(Model.Users, page => Url.Action("Index", new {
page,
sortOrder = Model.CurrentSort,
currentFilter = Model.CurrentFilter,
searchString = Model.CurrentFilter,
pageSize = Model.PageSize
}))
</div>
and in the controller method, initialize a new instance of UsersVM and assign its properties
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? pageSize)
{
UsersVM model = new UsersVM();
....
var users = from u in _db.USER select u;
....
pageSize = pageSize ?? 10;
model.PageSize = pageSize.Value;
model.Users = users.ToPagedList(pageNumber, pageSize);
model.PageSizeOptions = new List<SelectListItem> { .... };
return View(model);
}
My model looks something like this. It gets populated with items at some point by a stored procedure.
public class myModel
{
public List<SelectListItem> myList { get; set; }
public List<myModel> modelList { get; set; }
}
Here is my Controller.
[HttpGet]
public ActionResult getMyListItems()
{
var viewModel = new myModel();
viewModel.myList = viewModel.getMyList();
viewModel.modelList = viewModel.getMyModelList();
return View(viewModel);
}
Here is my view so far. I'm building a dropdownlist so the user can filter the contents of modelList. Kind of like a WHERE clause in an SQL query. Once the user selects the item and clicks the submit button, it applies the filter? Or would this happen after an item is actually selected in the dropdown without the need of a button click event?
#model SWAM2.Models.EmployeeOfcSpecKnow
#using CommonCode.HtmlHelpers;
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="editor-label">
Filter by Column1
</div>
<div class="editor-field">
#Html.DropDownListFor(model => Model.Column1, Model.myList, new { style = "width:400px" })
#Html.ValidationMessageFor(model => model.Column1)
</div>
<div class="toppad10">
<input type="submit" value="Apply Filter" />
</div>
<table class="grayTable rowStriping">
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
</thead>
<tbody>
#foreach (var item in #Model.modelList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Column1)
</td>
<td>
#Html.DisplayFor(modelItem => item.Column2)
</td>
<td>
#Html.DisplayFor(modelItem => item.Column3)
</td>
</tr>
}
</tbody>
</table>
}
You can achieve it by using dropdownlist change event.
refer :
on select change event - Html.DropDownListFor
onchange event for html.dropdownlist
One way to do this is by creating an action on your controller that returns a PartialViewResult and then using AJAX to asynchronously call that action and get the newly filtered list. So for example, you would create an action like this:
public PartialViewResult GetFilteredItems(string filter)
{
var viewModel = new myModel();
viewModel.myList = viewModel.getMyList();
viewModel.modelList = viewModel.getMyModelList();
viewModel.ApplyFilter(filter);
return PartialView(viewModel);
}
and call it using javascript, I prefer jQuery:
$("#dropDownListIdHere").change(function () {
$.ajax({
url: "#Url.Action("GetFilteredItems")",
method: "GET",
data: { filter: $(this).val() },
success: function (result) {
$("#listHolderIdHere").html(result);
}
})
});
Note that with this method, you'd need to create a partial view file (named GetFilteredItems if you don't want to specify a name in the controller action) that would contain the table to be rendered with the filtered items. You would also need to assign an ID to the dropdown and to some sort of container that you'd place your partial view into.
i would like to return below url from a search submit where id will be get from database.
So when a user search something by id it will search my database and display the result on my home view. then i want to transform my ID a clickable url which is this one:
http://myadress.com:8787/Handlers/DataExport.ashx?format=pdf&id=???&direction=0
Any idea how to do?
This is my home view:
<body>
<p>
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<b>SEARCH BY:</b> #Html.RadioButton("searchby", "ID", true) <text>ID</text>
#Html.RadioButton("searchby", "NAME") <text>NAME</text>
<br /><br />
#Html.TextBox("search") <input type="submit" value="SEARCH" />
}
</p>
<table>
<tr>
<th>
ID
</th>
<th>
NAME
</th>
<th>Actions</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan="2">NO DATA FOUND.</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.ActionLink("Details", "Details", new { id = item.id })
</td>
</tr>
}
}
this is my controller:
public class HomeController : Controller
{
private mydbEntities db = new mydbEntities();
//
// GET: /Home/
public ActionResult Index(string searchBy, string search)
{
if (searchBy == "ID")
{
return View(db.mytable.Where(x => x.ID == search).ToList());
}
else (searchBy == "NAME")
{
return View(db.mytable.Where(x => x.NAME == search).ToList());
}
}
You could just create an anchor tag and substitute the id in the href attribute
your link text
you have to use jquery for this. something like
$('.btnSearch').on('click', function(){
$('.lnkSubmit').attr('href', '#Url.Action("Action", "Controller", new { id = "----" })'.replace("----", (returned id here));
});
this will replace the url of a link with class lnkSubmit and will include the id that you put in it. Let me know if you have any questions.
In my Blog application, this is how I implemented search functionality for searching posts.
Partial view for search:
#using (Html.BeginForm("Search", "Blog", FormMethod.Get, new {id = "search-form"}))
{
<input type="text" name="s" placeholder="Search">
<button type="submit">Go</button>
}
Search action in controller:
public ActionResult Search(string s)
{
var model = _dbPostRepository.GetPostsForSearch(s);
ViewBag.TotalPosts = _dbPostRepository.TotalSearchPosts(s);
return View("Posts");
}
Posts View:
#model FirstBlog.Core.Post
#if (#ViewBag.TotalPosts > 0)
{
foreach (var item in Model)
{
Html.RenderPartial("_PostTemplate", item);
}
}
else
{
<p>No posts found!</p>
}
_PostTemplate is the view for each post. Hope this would help.
I have a form that I generate dynamically, based on the amount of rows in an Excel file that I upload. Where can I add logic that looks through the Description string and sets the dynamically generated dropdownlist to a specified value, based on text in the Description?
I want to add a list of checks, such as:
if "blabla" is in the Description string, set dropdownlist value to 4.
Do I have to do this in Javascript? Cause that doesn't feel that clean to me. I'd prefer my business logic be handled in my Controller, but I'm not sure how that would go in this design.
My code looks like this:
Preview page, which basically just links to my Editor Template named Transaction:
#using (Html.BeginForm("Preview", "Import", FormMethod.Post))
{
<table border="1" style="border-color: #FFFFFF">
#Html.EditorFor(m => m.Transactions, new { Categories = Model.Categories })
</table>
<input id="btnSave" type="submit" value="Opslaan in database" />
}
In this Editor Template transaction, I display some static data, and a textbox and dropdownlist for each row in the Excel that I have previously uploaded in another page:
<tr>
<td style="width: 40px; padding: 5px; background-color: #CurrencyHelper.GetCurrencyColor(Model.Amount)" align="right" nowrap="nowrap">#Html.Raw(CurrencyHelper.GetCurrency(Model.Currency, Model.Amount))
</td>
<td style="white-space: nowrap; padding: 5px;">#Model.DateTime.ToString("dd-MM-yyyy")
</td>
<td style="padding: 5px;">#Model.Description
</td>
<td style="padding: 5px;">#Html.EditorFor(m => m.ShortDescription)
</td>
<td style="padding: 5px;">#Html.DropDownListFor(m => m.CategoryId, new SelectList(ViewData["Categories"] as IEnumerable<Category>, "CategoryId", "Name"))
</td>
</tr>
My controller, which enters the data in the View Model:
//Attach unique Transactions and Categories to ViewModel
var viewModel = new ImportViewModel()
{
Transactions = uniqueTransactions.ToList(),
Categories = categoryRepository.GetCategories().OrderBy(c => c.Name).ToList()
};
Static Binding
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to the Training Courses...";
List objcourses = new List();
objcourses.Add("Asp.Net");
objcourses.Add("MVC");
objcourses.Add("WCF");
objcourses.Add("WPF");
objcourses.Add("C#.Net");
ViewBag.Courses = new SelectList(objcourses);
return View();
}
}
#{
ViewBag.Title = "Home Page";
}
Index
#using(#Html.BeginForm(“Index”,”Home”,FormMethod.Get)) {
Courses List; #Html.DropDownList(“Courses“)
}
Dynamic Binding
public class HomeController : Controller
{
public ActionResult Index()
{
private MovieDBContext db = new MovieDBContext();
var GenreLst = new List();
var GenreQry = from d in db.Movies
orderby d.Genre
select d.Genre;
GenreLst.AddRange(GenreQry.Distinct());
ViewBag.Courses = new SelectList(GenreLst);
return View();
}
}
#{
ViewBag.Title = "Home Page";
}
Index
#using(#Html.BeginForm("Index","Home",FormMethod.Get)) {
Courses List; #Html.DropDownList("Courses")
}