How to create pagination in asp.net mvc - c#

I want to make pagination with 5 articles per page using asp.net MVC,
what code should I add?
Here my controller:
using CBA.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CBA.ViewModels;
using System.Data;
namespace CBA.Controllers
{
public class EventController : Controller
{
private ModelEntities db = new ModelEntities();
public ActionResult Index()
//public ActionResult Index(int page = 1, int pageSize 5)
{
EventDetailsViewModel eventDetail = new EventDetailsViewModel();
MasterEvents events = new MasterEvents();
eventDetail.Title = events.Title;
eventDetail.CreatedTime = events.CreatedTime;
eventDetail.Detail = events.DetailEvent;
eventDetail.CreatedBy = events.CreatedBy_Id;
eventDetail.Description = events.ShortDescription;
CBA.GetContent.GetContentSoapClient service = new CBA.GetContent.GetContentSoapClient();
string[] Content = service.GetContentText("Events", DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));
if (Content[0] != null)
{
string id = Content[0];
string ContentText;
if (Content[1].Length == 0 && Content[2].Length == 0 && Content[3].Length == 0)
{
ContentText = "";
}
else
{
ContentText = "<div class=\"container\" #MARGIN-TOP# ><div class=\"row\"><div class=\"col-lg-10 col-lg-offset-1\">";
ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h1>" + Content[1] + "</h1></div>";
ContentText += "<div class=\"col-lg-12\" style=\"text-align:center;\"><h2>" + Content[2] + "</h2></div>";
ContentText += "<div class=\"col-lg-12\"><div class=\"form-group\">" + HttpUtility.HtmlDecode(Content[3]).Replace("src=\"/", "src=\"" + System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"] + "/") + "</div>";
ContentText += "</div></div></div>";
}
DataTable dtSlider = service.GetContentImageSlider(int.Parse(id), DateTime.Now.ToString("MM-dd-yyyy"), clsEncrypt.EncodeTo64(DateTime.Now.ToString("MM-dd-yyyy")));
if (dtSlider.Rows.Count > 0)
{
string ContentSlider = "<div id=\"myCarousel\" class=\"carousel slide\"><ol class=\"carousel-indicators\">";
for (int i = 0; i < dtSlider.Rows.Count; i++)
{
if (i == 0)
{
ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\" class=\"active\"></li>";
}
else
{
ContentSlider += "<li data-target=\"#myCarousel\" data-slide-to=\"" + i.ToString() + "\"></li>";
}
}
ContentSlider += "</ol><div class=\"carousel-inner\">";
for (int i = 0; i < dtSlider.Rows.Count; i++)
{
//dt.Columns.Add("ImageFile", typeof(string));
//dt.Columns.Add("HeaderText", typeof(string));
//dt.Columns.Add("ContentText", typeof(string));
string img = dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]);
if (i == 0)
{
ContentSlider +=
"<div class=\"item active\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
+ "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
+ "-o-background-size: cover;background-size: cover;\">"
+ "<div class=\"container\">"
+ "<div class=\"carousel-caption\">"
+ "<div class=\"col-lg-6\" style='width:260px;'>"
+ "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
+ "<p class=\"scroll_bni\" style='width: 260px;'>"
+ (string)dtSlider.Rows[i]["ContentText"]
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>";
}
else
{
ContentSlider +=
"<div class=\"item\" style=\"background:url('" + dtSlider.Rows[i]["ImageFile"].ToString().Replace("..", System.Configuration.ConfigurationManager.AppSettings["replaceURLImageSlider"]) + "') "
+ "no-repeat center center; -webkit-background-size: cover; -moz-background-size: cover; "
+ "-o-background-size: cover;background-size: cover;\">"
+ "<div class=\"container\">"
+ "<div class=\"carousel-caption\">"
+ "<div class=\"col-lg-6\" style='width:260px;'>"
+ "<h1>" + (string)dtSlider.Rows[i]["HeaderText"] + "</h1>"
+ "<p class=\"scroll_bni\" style='width: 260px;'>"
+ (string)dtSlider.Rows[i]["ContentText"]
+ "</p>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>";
}
}
ContentSlider += "</div><a class=\"left carousel-control\" href=\"#myCarousel\" data-slide=\"prev\"><span class=\"glyphicon glyphicon-chevron-left\"></span></a><a class=\"right carousel-control\" href=\"#myCarousel\" data-slide=\"next\"><span class=\"glyphicon glyphicon-chevron-right\"></span></a></div>";
ViewBag.Carousel = ContentSlider;
}
else
{
ContentText = ContentText.Replace("#MARGIN-TOP#", "style=\"margin-top:60px;\"");
}
ContentText = ContentText.Replace("#MARGIN-TOP#", "");
ViewBag.Content = ContentText;
}
return View(db.MasterEvents.ToList());
}
public ActionResult ViewEvents(int id)
{
MasterEvents MasterEvents = db.MasterEvents.Find(id);
ViewBag.data = id;
return View();
}
}
}
Here my view:
#model IEnumerable<CBA.Models.MasterEvents>
#{
ViewBag.Title = "Recruitment - DDR Events";
ViewBag.lnkEvents = "active";
Layout = "~/Views/Shared/ContentFrontEnd.cshtml";
}
<!-- Carousel
================================================== -->
#Html.Raw(ViewBag.Carousel)
<!-- /.carousel -->
<!-- Content
================================================== -->
#Html.Raw(ViewBag.Content)
<!-- /.Content -->
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div class="container" style="background-color: white; border-radius: 0 0 15px 15px; margin-bottom: 40px;">
<div class="row" style="margin-top: 30px;">
<div class="col-lg-10 col-lg-offset-1">
#foreach (var item in Model)
{
<div class="blog-post">
<h2 class="blog-post-title">#Html.DisplayFor(modelItem => item.Title)</h2>
<p class="blog-post-meta">
Created Time #Html.DisplayFor(modelItem => item.CreatedTime)
<!--by #Html.DisplayFor(modelItem => item.CreatedBy_Id)</p>-->
<h2 class="blog-post-title">#Html.DisplayFor(modelItem => item.ShortDescription)</h2>
<div class="readmore">
<p>
#{
string parameterValue = "";
if (item.DetailEvent.ToString().Length < 100)
{
parameterValue = item.DetailEvent;
}
else
{
parameterValue = item.DetailEvent.ToString().Substring(0, 200);
}
}
#Html.Raw(parameterValue);
</p>
</div>
<br />
#Html.ActionLink("Read More..", "ViewEvents", "Event", new { id = 7 }, new { #class = "btn btn-primary btn-lg", style = "width:180px;" })
</p>
<p class="blog-post-meta">
Update Time #Html.DisplayFor(modelItem => item.UpdatedTime)
<p>
</div>
}
<nav>
<ul class="pager">
<li>Previous</li>
<li>Next</li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
Here my models:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace CBA.Models
{
public class MasterEvents
{
[Key]
[DisplayName("ID")]
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required(ErrorMessage = "Required Events Title")]
[DisplayName("Title")]
[StringLength(250)]
public string Title { get; set; }
[Required(ErrorMessage = "Required Short Description")]
[DisplayName("Short Description")]
[StringLength(250)]
public string ShortDescription { get; set; }
[Required(ErrorMessage = "Required Details")]
[DisplayName("Detail Events")]
[StringLength(20)]
public string DetailEvent { get; set; }
[DisplayName("Created Time")]
public System.DateTime? CreatedTime { get; set; }
[DisplayName("Updated Time")]
public System.DateTime? UpdatedTime { get; set; }
[DisplayName("Created By")]
public int? CreatedBy_Id { get; set; }
[DisplayName("Updated By")]
public int? UpdatedBy_Id { get; set; }
}
}
How to make pagination, I want to make pagination with 5 articles per page..

Pagination in any system generally involves taking a page number and a count per page in the controller method so that you can then pass these values to your search method in the business layer or data access layer to get only the content that you need.
So essentially:
Modify the Index controller method to something like this: Index(int page = 1, int countPerPage = 5)
This will allow you to pass the page number and count per page in the controller which you can then use to pass to the search method.
You will also need to create a UI which shows the page numbers. One way to calculate how many pages you will need to show is by returning the TOTAL number of items present in the search (from your search method) and then dividing this by the countPerPage value.
I hope this pushes you in the right direction.
Here are some resources for further reading:
How do I do pagination in ASP.NET MVC?
and
http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
which should give you a better idea.

Related

How do you move data from one cell in one row of a web grid to another cell in another row that is empty using jQuery?

I am kind of lost when it comes to jQuery sometimes, though I know there is a way! How do you update or move three cells data to another row based on the rows id to where the row is green (empty cells)? The row column ID name is "LocationID". MVC application using a web grid. What I am trying to do is when I check the row, use the drop-down that has the id, send the data to that row where the id exists populating the three empty cells in green with the current columnar data row that is checked. Any help would be greatly appreciated!
WebGrid below:
enter
<div id="content">
#webGrid.GetHtml(tableStyle: "webgrid-table",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
//alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
rowStyle: "webgrid-row-style",
mode: WebGridPagerModes.All,
htmlAttributes: new { #id = "webGrid" },
columns: webGrid.Columns(
webGrid.Column(header: "Actions", format:#<span class="link">
<!--Add Checkbox here-->
<!-- Note: We can add clickable rows as an option for user using a checkbox, one
selects the data move and the other move to selection. -->
#Html.CheckBoxFor(model => model.SelectedMoveIsChecked, new { #Class =
"SelectedMoveIsChecked", #id = "SelectedMoveIsChecked", #checked = false })
#Html.CheckBoxFor(model => model.SelectedMoveToChecked, new { #Class =
"SelectedMoveToChecked", #id = "SelectedMoveToChecked", #checked = false })
<!-- Html.CheckBox("isActive", false, item.isSelectdRow, true, new { id =
"CheckBoxSelectedBeginMove", Class = "CheckBoxIsSelected" })
Html.CheckBoxFor(Model.Input_Location, item.isSelectdRow, new { = "'SelectedRows'",
data_val = item.Location })
-->
<a class="Edit" href="javascript:;">Edit</a>
<a class="Clear" href="javascript:;">Clear</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</span>),
webGrid.Column(header: "Location", format: #<div>
<label id="LocationLbl" class="label">#item.Location</label>
<input id="Location" class="text" type="text" value="#item.Location" style="display:none"
/><br />
#Html.DropDownListFor(model => model.LocationAppended, Model.LocationAppended,
"Section/Location", new { IReadOnlyDictionary = "document.forms[0].submit();", #id =
"RowLocationDropDownList", #class = "RowLocationDropDownList", #visibility = "hidden",
#placeholder = "Location" })
</div>, style: "Location"),
webGrid.Column(header: "Section", format: #<div>
<label id="SectionLbl" class="label">#item.Section</label>
<input id="Section" class="text" type="text" value="#item.Section" style="display:none" />
</div>, style: "Section"),
webGrid.Column(header: "TrailerNumber", format: #<div>
<label id="TrailerNumberLbl" class="label">#item.TrailerNumber</label>
<input id="TrailerNumber" class="text" type="text" value="#item.TrailerNumber"
style="display:none" />
</div>, style: "TrailerNumber"),
webGrid.Column(header: "CarrierName", format: #<div>
<label id="CarrierNameLbl" class="label">#item.CarrierName</label>
<input id="CarrierName" class="text" type="text" value="#item.CarrierName"
style="display:none" />
</div>, style: "CarrierName"),
webGrid.Column(header: "LoadCommodityStatus", format: #<div>
<label id="LoadCommodityStatusLbl" class="label">#item.LoadCommodityStatus</label>
<input id="LoadCommodityStatus" class="text" type="text" value="#item.LoadCommodityStatus"
style="display:none" />
</div>, style: "LoadCommodityStatus"),
webGrid.Column(header: "DateLoaded", format: #<div>
<label id="DateLoadedLbl" class="label">#item.DateLoaded</label>
<input id="DateLoaded" class="text" type="text" value="#item.DateLoaded" style="display:none"
/>
</div>, style: "DateLoaded"),
webGrid.Column(header: "UserName", format: #<div>
<label id="UserNameLbl" class="label">#item.UserName</label>
<input id="UserName" class="text" type="text" value="#item.UserName" style="display:none" />
</div>, style: "UserName"),
webGrid.Column(header: "PlantLocation", format: #<div>
<label id="PlantLocationLbl" class="label">#item.PlantLocation</label>
<input id="PlantLocation" class="text" type="text" value="#item.PlantLocation"
style="display:none" />
</div>, style: "PlantLocation"),
webGrid.Column(header: "RowPageID", format: #<div>
<label id="LocationIDLbl" class="label">#item.LocationID</label>
</div>, style: "LocationID"))),
<div id="RowCountBpttom"><b>Records: #firstRecord - #lastRecord of
#webGrid.TotalRowCount</b></div>
</div>
<br />
<div class="WebGridTable">
</div>
</div>
</form>
</div>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">
</script>
<script src="~/Scripts/YardDogAdmin.js"></script>
</body>
jQuery Below:
code here
enter
$('select.RowLocationDropDownList').attr('disabled', true);
$(".SelectedMoveIsChecked").change(function (i, row) {
$actualRowColorRed = $(row);
//When a value is selected in the dropdownlist box.
if ($(this).children("option:selected").val() != '') {
$("select.RowLocationDropDownList").change(function (i, row) {
$actualRowColorRed = $(row);
//Checks to see if the checkbox is checked, display the alert showing data and color the row red again.
/////// if ($('.SelectedMoveIsChecked').is(':checked') == true) {
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[0];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[1];
var RowLocation = ret[2];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
// var ConfirmStr = " <b>Are you sure, you want to move this row From: </b>" + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
// alert("Alert " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?"
// );
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
//Add new values to (TrailerNumber, CarrierName, LoadCommodityStatus, DateLoaded, UserName).
//Note: Get the UserName currently using the Yard Dog Application.
/// $('#webGrid').closest('tr').find('#TrailerNumber').val();
/// $("#webGrid tbody tr").each(function (i, row) {
// $('#webGrid tbody tr').find('#LocationID'.val(RowLocationIDNum); //= RowLocationIDNum).append('#TrailerNumber'.val(CurrentRowTrailerNumber));
$("body").on("change", "select.RowLocationDropDownList", function () {
// $("body").on("click", "#webGrid TBODY .Update", function () {
// $("#content").on("click", "#webGrid INPUT", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
span.html(input.val());
}
});
//// $('#webGrid tbody tr').find('#LocationID').val(RowLocationIDNum) = customer;
var RowExchange = $(RowLocationID).closest("tr");
var ToRow = {};
ToRow.LocationID = row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
/*
ToRow.LocationID = RowExchange.find('#LocationID').append(RowLocationID) ;
ToRow.UserName = RowExchange.find('.UserName').append(row.find(".UserName").find(".label").html());
ToRow.Location = RowExchange.find('.Location').append(row.find(".Location").find(".label").html());
ToRow.Section = RowExchange.find('.Section').append(row.find(".Section").find(".label").html());
ToRow.TrailerNumber = RowExchange.find('.TrailerNumber').append(ToRow.TrailerNumber);
ToRow.CarrierName = RowExchange.find('.CarrierName').val().append(ToRow.CarrierName);
ToRow.LoadCommodityStatus = RowExchange.find('.LoadCommodityStatus').append(ToRow.LoadCommodityStatus);
ToRow.DateLoaded = RowExchange.find('.DateLoaded').append(row.find(".DateLoaded").find(".label").html());
ToRow.PlantLocation = RowExchange.find('.PlantLocation').append(row.find(".PlantLocation").find(".label").html());
*/
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) +'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 777);
});
}
else {
confirm_value.value = "Cancel";
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
code here
Controller:
enter [HttpPost]
public ActionResult UpdateRowExchange(LocationData ToRow)
{
using (PW_YardDogDataEntitiesModel3 entities = new PW_YardDogDataEntitiesModel3())
{
LocationData updatedCustomer = (from c in entities.LocationDatas
where c.LocationID == ToRow.LocationID
select c).FirstOrDefault();
//Check for Duplicates.
///FindDuplicates(customer);
//HighlightDuplicate(webGrid);
//x => customer.TrailerNumber == x.TrailerNumber && x.TrailerNumber == customer.TrailerNumber //errases all data except the first cell TrailerNumber.
if (ToRow.UserName != null) updatedCustomer.UserName = ToRow.UserName.ToUpper();
else updatedCustomer.UserName = ToRow.UserName = null;
/*
if (customer.Location != null) updatedCustomer.Location = customer.Location.ToUpper();
else updatedCustomer.Location = customer.Location = null;
if (customer.Section != null) updatedCustomer.Section = customer.Section.ToUpper();
else updatedCustomer.Section = customer.Section = null;
*/
if (ToRow.TrailerNumber != null) updatedCustomer.TrailerNumber = ToRow.TrailerNumber.ToUpper();
else updatedCustomer.TrailerNumber = ToRow.TrailerNumber = null;
if (ToRow.CarrierName != null) updatedCustomer.CarrierName = ToRow.CarrierName.ToUpper();
else updatedCustomer.CarrierName = ToRow.CarrierName = null;
if (ToRow.LoadCommodityStatus != null) updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus.ToUpper();
else updatedCustomer.LoadCommodityStatus = ToRow.LoadCommodityStatus = null;
if (ToRow.DateLoaded != null) updatedCustomer.DateLoaded = ToRow.DateLoaded.ToUpper();
else updatedCustomer.DateLoaded = ToRow.DateLoaded = null;
/*
if (customer.PlantLocation != null) updatedCustomer.PlantLocation = customer.PlantLocation.ToUpper();
else updatedCustomer.PlantLocation = customer.PlantLocation = null;
*/
//Create today's Date for a timestamp of inputs.
DateTime now = DateTime.Today;
ToRow.DateLoaded = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss tt");
updatedCustomer.DateLoaded = ToRow.DateLoaded;
entities.SaveChanges();
//Refresh(out, customer.ToString());
}
return new EmptyResult();
}
code here
Model below:
enter code here
namespace YardDog.Model
{
public class YardDogModel
{
ContYardDogAdmin ContYardDogData = new ContYardDogAdmin();
//Two Properties for DropDownList.
public List<LocationData> LocationDatas { get; set; }
//public List<LocationData> Location { get; set; }
public List<LocationData> TrailerNumber { get; set; }
public List<SelectListItem> PlantLocation { get; set; }
public List<SelectListItem> Location { get; set; }
public List<SelectListItem> LocationList { get; set; }
public List<SelectListItem> SectionList { get; set; }
public List<SelectListItem> LocationAppended { get; set; }
[Display(Name = "Name")]
public List<SelectListItem> Section { get; set; }
public List<SelectListItem> ListDuplicates { get; set; }
public List<SelectListItem> UserName { get; set; }
//Allow the data to be transfered (Backend into SQL Server).
[Required]
public string Input_Location { get; set; }
[Required]
public string Input_Section { get; set; }
public string Input_TrailerNumber { get; set; }
public string Input_CarrierName { get; set; }
public string Input_CommodityLoadStatus { get; set; }
[Required]
public string Input_PlantLocation { get; set; }
//YardDogModel YardDogDatas = new YardDogModel();
//string TrailerNumber = Input_TrailerNumber;
public bool SelectedMoveIsChecked { get; set; } = false;
public bool SelectedMoveToChecked { get; set; } = false;
public string LocationAppendedLbl { get; internal set; }
//public string LocationAppended { get; internal set; }
public string RowLocationDropDownList { get; set; }
public int RowLocationIDNum { get; set; }
}
}
JavaScript:
$('select.RowLocationDropDownList').children("option:selected").val();
var str = $(this).children("option:selected").val();
var ret = str.split(" ");
var RowLocationID = ret[2];
var RowLocationIDNum = parseInt(RowLocationID); //convert string to int.
var RowSection = ret[0];
var RowLocation = ret[1];
var CurrentRowID = $(this).closest("tr").find('#LocationIDLbl').text();
var CurrentRowLocation = $(this).closest("tr").find('#LocationLbl').text();
var CurrentRowSection = $(this).closest("tr").find('#SectionLbl').text();
var CurrentRowTrailerNumber = $(this).closest("tr").find('#TrailerNumberLbl').text();
var CurrentRowCarrierName = $(this).closest("tr").find('#CarrierNameLbl').text();
var CurrentRowLoadCommodityStatus = $(this).closest("tr").find('#LoadCommodityStatusLbl').text();
var CurrentRowDateLoaded = $(this).closest("tr").find('#DateLoadedLbl').text();
var CurrentRowUserName = $(this).closest("tr").find('#UserNameLbl').text();
var CurrentRowPlantLocation = $(this).closest("tr").find('#PlantLocationLbl').text();
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
var ConfirmStr = "Are you sure, you want to move this row From: " + CurrentRowID + " Section: " + CurrentRowSection + " Location:" + CurrentRowLocation + " TrailerNumber:" + CurrentRowTrailerNumber + " \n\n\n To \n Section: ";
if (confirm("Confirm! " + ConfirmStr + "Original: " + str + " RowPageID: " + RowLocationIDNum + " Section: " + RowSection + " Location: " + RowLocation + "?")) {
confirm_value.value = "Yes";
$("body").on("change", "select.RowLocationDropDownList", function () {
var row = $(this).closest("tr");
$("webGrid td", row).each(function () {
if ($(this).find(".text").length > 0) {
span.html(input.val());
}
});
//Tell the row change to be where ID exists by ID Number (RowLocationIDNum).
var ToRow = {};
ToRow.LocationID = RowLocationIDNum; //row.find(".LocationID").find(".label").html();
ToRow.UserName = row.find(".UserName").find(".label").html();
ToRow.Location = row.find(".Location").find(".label").html();
ToRow.Section = row.find(".Section").find(".label").html();
ToRow.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
ToRow.CarrierName = row.find(".CarrierName").find(".label").html();
ToRow.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
ToRow.DateLoaded = row.find(".DateLoaded").find(".label").html();
ToRow.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/UpdateRowExchange",
data: '{ToRow:' + JSON.stringify(ToRow) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
// setInterval('location.reload()', 777);
//Set the Clear Event to clear the initial rows.
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find(".text").length > 0) {
var span = $(this).find(".label");
var input = $(this).find(".text");
$(this).find(".text").show();
$(this).find(".label").hide();
span.html(input.val(null));
span.show();
input.hide();
}
});
row.find(".Cancel").show();
row.find(".Clear").show();
row.find(".Edit").show();
$(this).hide();
var clear = {};
clear.LocationID = row.find(".LocationID").find(".label").html();
clear.UserName = row.find(".UserName").find(".label").html();
clear.Location = row.find(".Location").find(".label").html();
clear.Section = row.find(".Section").find(".label").html();
clear.TrailerNumber = row.find(".TrailerNumber").find(".label").html();
clear.CarrierName = row.find(".CarrierName").find(".label").html();
clear.LoadCommodityStatus = row.find(".LoadCommodityStatus").find(".label").html();
clear.DateLoaded = row.find(".DateLoaded").find(".label").html();
clear.PlantLocation = row.find(".PlantLocation").find(".label").html();
$.ajax({
type: "POST",
url: "/Home/ClearCustomer",
data: '{clear:' + JSON.stringify(clear) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}); setInterval('location.reload()', 500);
});
}
else {
confirm_value.value = "Cancel";
setInterval('location.reload()', 500);
}
document.forms[0].appendChild(confirm_value);
}
Confirm();
});
}
});

Html not displaying in View that was created in Controller

When I created a method in a controller I would like the output which is HTML to be displayed in the view. Although I see the functions results as the expected html it does not display in the page.
I've tried the HtmlHelper Html.Raw
<table class="table table-bordered table-framed" id="seconDTable" style="display:block;height:100%;">
<tbody>
#if (caseFile.Length > 0 && RenamedCaseFileName.Length > 0)
{
<tr>
<td style="width: 100%;">
<input type="checkbox" id="CheckBox" title="Select All Bookmarks" onchange="changeCheckBox();" class="styled" />
<span>Select All</span>
</td>
</tr>
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.OK)
{
int rootID = oGdPicturePDF.GetBookMarkRootID();
oGdPicturePDFstatus = oGdPicturePDF.GetStat();
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.OK)
{
IHtmlString str = new HtmlString(GetPDFBookmarks.ParseBookmarksOutlines(oGdPicturePDF, rootID, 0));
Html.Raw(str);
}
else
{
if (oGdPicturePDFstatus == GdPicture14.GdPictureStatus.PropertyNotFound)
{
<tr>
<td style="width: 100%;">
This PDF document doesn't contain any bookmarks.
</td>
</tr>
}
}
}
oGdPicturePDF.Dispose();
}
</tbody>
</table>
Function:
public string ParseBookmarksOutlines(GdPicturePDF oGdPicturePDF, int bookmarkID, int level)
{
string title = "";
GdPictureStatus status = GdPictureStatus.OK;
string cssType = string.Empty;
string TableRows = string.Empty;
while (true)
{
title = oGdPicturePDF.GetBookMarkTitle(bookmarkID);
status = oGdPicturePDF.GetStat();
if (level == 0)
{
cssType = "ParentsourcefileCheckBox";
}
else
{
cssType = "ChildsourcefileCheckBox";
}
if (status == GdPictureStatus.OK)
{
TableRows = TableRows + "<tr><td style=\"width: 100 %; \">";
TableRows = TableRows + "<input name=\"sourcefileCheckBox\" type=\"checkbox\" class=\"" + cssType + "\" id=\"checkBox\" value=\"" + bookmarkID + "\" />";
TableRows = TableRows + "<span>" + title + "</span>";
TableRows = TableRows + "</td></tr>";
}
else
{
TableRows = TableRows + "<tr><td>";
TableRows = TableRows + "Title: this error occurs - " + status.ToString() + " Level: " + level.ToString() + "\n";
TableRows = TableRows + "</td></tr>";
//message = message + "Title: this error occurs - " + status.ToString() + " Level: " + level.ToString() + "\n";
}
if (bookmarkID == 0)
{
break;
}
}
return TableRows;
}
I'm expecting the checkboxes to be displayed on the final rendered page instead it does not display ay all.
enter image description here
The answer was the following:
#Html.Raw(HttpUtility.HtmlDecode(GetPDFBookmarks.ParseBookmarksOutlines(oGdPicturePDF, rootID, 0)));
It was located in the post:
Return html string from controller and display in view

How to bind data to grid column using array

aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="V_MaterCode.aspx.cs" Inherits="V_MaterCode" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "V_MaterCode.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#grd_mastercodes").append("<tr><td>" + data.d[i].Vendor + "</td><td>" + data.d[i].SearchTerm + "</td><td>" + data.d[i].Vendor_Name + "</td><td>" + data.d[i].Street + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td><td>" + data.d[i].PO_Box + "</td><td>" + data.d[i].Currency + "</td><td>" + data.d[i].Sales_Person + "</td><td>" + data.d[i].Telephone_Number + "</td><td>" + data.d[i].Ext_01 + "</td><td>" + data.d[i].Ext_02 + "</td><td>" + data.d[i].Minimum_Value + "</td><td>" + data.d[i].Post_Code + "</td><td>" + data.d[i].Group + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" LoadScriptsBeforeUI="false"
EnablePartialRendering="false">
</asp:ScriptManager>
<div class="contentarea">
<br />
<asp:Label ID="lblsub" Style="overflow-x: auto; margin-left: 20px;" runat="server" Text="Station master data entry" />
</div>
<div style="margin: 0 auto; overflow: auto; padding: 10px 20px;">
<asp:GridView ID="grd_mastercodes" runat="server" HeaderStyle-BackColor="#f79646" HeaderStyle-ForeColor="White"
HeaderStyle-Font-Bold="false" Font-Names="Calibri"
Font-Size="Medium" RowStyle-BackColor="White" HeaderStyle-BorderColor="Black"
AutoGenerateColumns="False" RowStyle-BorderColor="Black" OnRowCreated="grd_mastercodes_RowCreated">
</asp:GridView>
</div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using AjaxControlToolkit;
public partial class V_MaterCode : System.Web.UI.Page
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
bool rowset = false;
GridView dgv = new GridView();
// For First gridview
String[] gridColumnNames_mastercodes = { "Vendor Code", "Search Term", "Vendor Name", "Street", "City", "Country", "Post Box", "Currency", "Sales Person", "Telephone Number", "Ext_01", "Ext_02", "Minimum Value", "Post Code", "Group" };
String[] gridColumnwidth_mastercodes = { "50px", "200px", "200px", "150px", "100px", "100px", "100px", "100px", "150px", "150px", "150px", "150px", "100px", "100px", "100px" };
int[] gridColumnWidth_mastercodes = { 3, 15, 15, 13, 10, 10, 10, 10, 13, 13, 13, 13, 10, 10, 10 };
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
//For First gridview
DataTable dt = new DataTable();
for (int c = 0; c < gridColumnNames_mastercodes.Length; c++)
{
DataColumn dcol = new DataColumn(c.ToString(), typeof(System.Int32));
dcol.ColumnName = gridColumnNames_mastercodes[c];
dt.Columns.Add(dcol);
TemplateField tf = new TemplateField();
tf.HeaderStyle.Font.Bold = false;
tf.HeaderText = gridColumnNames_mastercodes[c];
tf.HeaderStyle.Width = new Unit(gridColumnwidth_mastercodes[c]);
grd_mastercodes.Columns.Add(tf);
}
for (int i = 0; i < 15; i++)
{
dt.Rows.Add(dt.NewRow());
}
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("Vendor");
dt.Columns.Add("Search Term");
dt.Columns.Add("Vendor Name");
dt.Columns.Add("Street");
dt.Columns.Add("City");
dt.Columns.Add("Country");
dt.Columns.Add("Post Box");
dt.Columns.Add("Currency");
dt.Columns.Add("Sales Person");
dt.Columns.Add("Telephone Number");
dt.Columns.Add("Ext_01");
dt.Columns.Add("Ext_02");
dt.Columns.Add("Minimum Value");
dt.Columns.Add("Post Code");
dt.Columns.Add("Group");
dt.Rows.Add();
grd_mastercodes.DataSource = dt;
grd_mastercodes.DataBind();
//grd_mastercodes.Rows[0].Visible = false;
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(connectionstring))
{
using (SqlCommand cmd = new SqlCommand("Select * From ArR_VendorMaster", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Vendor = dtrow["Vendor"].ToString();
user.SearchTerm = dtrow["SearchTerm"].ToString();
user.Vendor_Name = dtrow["Vendor_Name"].ToString();
user.Street = dtrow["Street"].ToString();
user.City = dtrow["City"].ToString();
user.Country = dtrow["Country"].ToString();
user.PO_Box = dtrow["PO_Box"].ToString();
user.Currency = dtrow["Currency"].ToString();
user.Sales_Person = dtrow["Sales_Person"].ToString();
user.Telephone_Number = dtrow["Telephone_Number"].ToString();
user.Ext_01 = dtrow["Ext_01"].ToString();
user.Ext_02 = dtrow["Ext_02"].ToString();
user.Minimum_Value = dtrow["Minimum_Value"].ToString();
user.Post_Code = dtrow["Post_Code"].ToString();
user.Group = dtrow["Group"].ToString();
details.Add(user);
}
}
}
return details.ToArray();
}
public class UserDetails
{
public string Vendor { get; set; }
public string SearchTerm { get; set; }
public string Vendor_Name { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PO_Box { get; set; }
public string Currency { get; set; }
public string Sales_Person { get; set; }
public string Telephone_Number { get; set; }
public string Ext_01 { get; set; }
public string Ext_02 { get; set; }
public string Minimum_Value { get; set; }
public string Post_Code { get; set; }
public string Group { get; set; }
}
//For First Gridview
protected void grd_mastercodes_RowCreated(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int rc = 0; rc < grd_mastercodes.Columns.Count; rc++)
{
TextBox txtBox = new TextBox();
txtBox.ID = "Excel_mastercodes" + e.Row.RowIndex + "_" + rc;
txtBox.MaxLength = gridColumnWidth_mastercodes[rc];
txtBox.Width = new Unit(gridColumnwidth_mastercodes[rc]);
txtBox.BorderStyle = BorderStyle.None;
e.Row.Cells[rc].Controls.Add(txtBox);
e.Row.Cells[rc].Attributes.Add("onKeyDown", "enter(this);");
if (rc == 3)
txtBox.Style["text-align"] = "left";
else
txtBox.Style["text-align"] = "center";
}
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
}
}
}
I need to bind data but it displaying column name only . It's not binding any data . weather i am doing in a correct . If any body knows how to get data please suggest me. I am using array and i am not sure how to bind data in array . I need your help

Issues with variable length lists and Validation Errors in MVC 4

I am currently working on a form using asp.net-mvc 4 that submits an object with a variable number of sub-objects stored in an IList.
I'm running in to an issue with validation messages being attached to the incorrect object in the IList if an error is returned. If the first object in the list is deleted and the second object (that then becomes the first) has errors in it, the incorrect object does not get the correct validation result on page reload. The object in the list that had an index of 3 is given an index of 2 when the error is returned, which also changes the previous (possibly correct) selections at the same time.
Is there any way to change which objects in a list the previous validation errors get attached to?
Edit: The validation messages are in the correct location because the "ValidationIndex" is working, the highlighting is where I'm having the issue.
I've tried adding in a "ValidationIndex" to the objects in the list to send the validation errors to the correct place. This has worked for the error message but the incorrect object is still having its fields highlighted and changed.
Removing the ability to delete anything except the last object would obviously be one way to solve this issue, but I'm really hoping to find a way to keep the functionality. I'd also like to avoid having to make an http request every time a new box is added if at all possible.
Here is an imgur album showing the issue:
http://imgur.com/a/borWG
Here is an example of the code I'm using:
The container class:
public class TestProduct : Product
{
public IList<TestItem> TItems { get; set; }
public TestProduct()
{
TItems = new List<TestItem>();
}
}
The class in the list:
public class TestItem : IValidatableObject
{
[Display(Name = "Select 1")]
public string select1 { get; set; }
[Display(Name = "Select 2")]
public string select2 { get; set; }
// Added to try and Identify where the validation errors need to go
public int ValidationIndex { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (select1 == null)
{
yield return new ValidationResult("Required", new string[] { "select1" });
}
if (select2 == null)
{
yield return new ValidationResult("Required", new string[] { "select2" });
}
if (select1 == select2)
{
yield return new ValidationResult("The options cannot be the same", new string[] { "select2", "select1" });
}
}
}
The View:
#model TestProduct
#{
List<SelectListItem> selectOptions = new List<SelectListItem>()
{
new SelectListItem { Text = "Choose...", Value = "" },
new SelectListItem { Text = "Option 1", Value = "o1" },
new SelectListItem { Text = "Option 2", Value = "o2" },
new SelectListItem { Text = "Option 3", Value = "o3" },
new SelectListItem { Text = "Option 4", Value = "o4" }
};
}
<script type="text/javascript">
$(document).ready(function () {
var itemContainer = $('#items');
var i = $('#items .item-option').length;
$('#addItem').on("click", function (e) {
if ($('#items .item-option').length <= 15) {
var newField = '<fieldset class="item-option"> ' +
'<legend>Item ' + (i + 1) + '</legend>' +
'<input type="hidden" name="TItems.Index" value="' + i + '" /> ' +
'<input type="hidden" name="TItems[' + i + '].ValidationIndex" value="' + i + '" /> ' +
'<div class="line"> ' +
'<div> ' +
'<div class="label"><label for="select1-' + i + '">#Html.DisplayNameFor(model => model.TItems[0].select1)</label></div> ' +
'<div> ' +
'<select id="select1-' + i + '" name="TItems[' + i + '].select1"> ' +
#foreach (SelectListItem so in selectOptions)
{
<text>
'<option value="#so.Value">#so.Text</option> ' +
</text>
}
'</select> ' +
'</div> ' +
'</div> ' +
'<div> ' +
'<div class="label"><label for="select2-' + i + '">#Html.DisplayNameFor(model => model.TItems[0].select2)</label></div> ' +
'<div>' +
'<select id="select2-' + i + '" name="TItems[' + i + '].select2"> ' +
#foreach (SelectListItem so2 in selectOptions)
{
<text>
'<option value="#so2.Value">#so2.Text</option> ' +
</text>
}
'</select> ' +
'</div> ' +
'</div> ' +
'</div> ' +
'<div class="pos-rb"><button class="remItem smalltext">Remove</button></div> ' +
'</fieldset>';
itemContainer.append(newField);
$('.remItem:hidden').show();
i++;
}
e.preventDefault();
});
$('#items').on("click", '.remItem', function (e) {
var n = $('#items .item-option').length;
if (n >= 2) {
$(this).closest('.item-option').remove();
}
if (n == 2) {
$('.remItem').hide();
}
e.preventDefault();
});
});
</script>
<h3>Test Product</h3>
<div class="indented">
<div id="items" class="items question">
#if (Model.TItems.Count > 0)
{
for (int i = 0; i < Model.TItems.Count; i++)
{
int validationIndex = Model.TItems[i].ValidationIndex;
<text>
<fieldset class="item-option">
<legend>Item #(i + 1)</legend>
<input type="hidden" name="TItems.Index" value="#i" />
<input type="hidden" name="TItems[#i].ValidationIndex" value="#i" />
<div class="line">
<div>
<div class="label">#Html.LabelFor(model => model.TItems[i].select1)</div>
<div>
#Html.DropDownListFor(model => model.TItems[i].select1, new SelectList(selectOptions, "Value", "Text", Model.TItems[i].select1))<br />
#Html.ValidationMessageFor(model => model.TItems[validationIndex].select1)
</div>
</div>
<div>
<div class="label">#Html.LabelFor(model => model.TItems[i].select2)</div>
<div>
#Html.DropDownListFor(model => model.TItems[i].select2, new SelectList(selectOptions, "Value", "Text", Model.TItems[i].select2))<br />
#Html.ValidationMessageFor(model => model.TItems[validationIndex].select2)
</div>
</div>
</div>
<div class="pos-rb">
<button class="remItem smalltext" #if (Model.TItems.Count == 1) { <text> style="display: none;" </text> }>Remove</button>
</div>
</fieldset>
</text>
}
}
else
{
<text>
<fieldset class="item-option">
<legend>Item 1</legend>
<input type="hidden" name="TItems.Index" value="0" />
<input type="hidden" name="TItems[0].ValidationIndex" value="0" />
<div class="line">
<div>
<div class="label">#Html.LabelFor(model => model.TItems[0].select1)</div>
<div>
#Html.DropDownListFor(model => model.TItems[0].select1, new SelectList(selectOptions, "Value", "Text"))
</div>
</div>
<div>
<div class="label">#Html.LabelFor(model => model.TItems[0].select2)</div>
<div>
#Html.DropDownListFor(model => model.TItems[0].select2, new SelectList(selectOptions, "Value", "Text"))
</div>
</div>
</div>
<div class="pos-rb"><button class="remItem smalltext" style="display: none;">Remove</button></div>
</fieldset>
</text>
}
</div>
<button id="addItem" class="smalltext" style="margin-left: 2em;">Add Another Item</button>
<br />
<div style="margin: 1em;"><input type="submit" value="Calculate" /></div>
</div>
Edit:
I figured out a rather messy work around using JavaScript. Every time an item is removed it goes through and replaces all the names, ids, and for fields for all the inputs and their labels in the form. It's not exactly elegant, but it's working so far...
Here's the new remove item event handler:
$('#items').on("click", ".remItem", function (e) {
var n = $("#items .item-option").length;
if (n >= 2) {
$(this).closest(".item-option").remove();
}
if (n == 2) {
$(".remItem").hide();
}
$("#items").find(".item-option").each(function (index) {
$(this).find(".item-index").val(index);
$(this).find("select, input, textarea").each(function () {
var name1 = $(this).attr('name');
if (name1 != null) {
var name2 = name1.replace(/TItems\[\d+\]/, "TItems[" + index + "]");
$(this).attr("name", name2);
}
var id1 = $(this).attr("id");
if (id1 != null) {
var id2 = id1.replace(/_\d+__/, "_" + index + "__");
$(this).attr("id", id2);
}
});
$(this).find("label").each(function () {
var for1 = $(this).attr("for");
if (for1 != null) {
var for2 = for1.replace(/_\d+__/, "_" + index + "__");
$(this).attr("for", for2);
}
});
$(this).find("legend").html("Item " + (index+1));
});
i--;
e.preventDefault();
});

Binding a view model in ASP.NET MVC for contact form

I haven't been building ASP.NET MVC websites for very long, so I'm not sure where I'm going wrong with my view model? I'm trying to build a contact form for a website, however when I click "Submit" the form will completely ignore the JavaScript validation as well as the if (ModelState.IsValid) statement?!
I wasn't sure if it's because I'm not passing the model into my controller POST method?
I'd really appreciate if someone with more experience in ASP.NET MVC could take a look.
Thanks!
My view:
#model ThePines.ViewModels.EnquiryForm
#using (Html.BeginForm("Index", "Enquiries", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
#Html.ValidationSummary(true)
<fieldset>
<table cellpadding="8" cellspacing="8">
<tr>
<td>#Html.LabelFor(model => model.FirstName, "First Name")</td>
<td>#Html.TextBoxFor(model => model.FirstName, new { #class = "medium" })</td>
<td>#Html.ValidationMessageFor(model => model.FirstName)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.LastName, "Last Name")</td>
<td>#Html.TextBoxFor(model => model.LastName, new { #class = "medium" })</td>
<td>#Html.ValidationMessageFor(model => model.LastName)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.EmailAddress, "Email Address")</td>
<td>#Html.TextBoxFor(model => model.EmailAddress, new { #class = "long" })</td>
<td>#Html.ValidationMessageFor(model => model.EmailAddress)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Country, "Country")</td>
<td>#Html.TextBoxFor(model => model.Country, new { #class = "medium" })</td>
<td>#Html.ValidationMessageFor(model => model.Country)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.PartySize, "Party Size")</td>
<td>#Html.DropDownListFor(model => model.PartySize, new SelectList(ViewBag.PartySizes), "Party Size")</td>
<td>#Html.ValidationMessageFor(model => model.PartySize)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.ArrivalDay, "Arrival Date")</td>
<td>#Html.DropDownListFor(model => model.ArrivalDay, new SelectList(ViewBag.ArrivalDay), "Day") #Html.DropDownListFor(model => model.ArrivalMonth, new SelectList(ViewBag.ArrivalMonth), "Month") #Html.DropDownListFor(model => model.ArrivalYear, new SelectList(ViewBag.ArrivalYear), "Year")</td>
<td>#Html.ValidationMessageFor(model => model.ArrivalDay) #Html.ValidationMessageFor(model => model.ArrivalMonth) #Html.ValidationMessageFor(model => model.ArrivalYear)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.DepartureDay, "Departure Date")</td>
<td>#Html.DropDownListFor(model => model.DepartureDay, new SelectList(ViewBag.DepartureDay), "Day") #Html.DropDownListFor(model => model.DepartureMonth, new SelectList(ViewBag.DepartureMonth), "Month") #Html.DropDownListFor(model => model.DepartureYear, new SelectList(ViewBag.DepartureYear), "Year")</td>
<td>#Html.ValidationMessageFor(model => model.DepartureDay) #Html.ValidationMessageFor(model => model.DepartureMonth) #Html.ValidationMessageFor(model => model.DepartureYear)</td>
</tr>
<tr>
<td>#Html.LabelFor(model => model.Question, "Question")</td>
<td>#Html.TextAreaFor(model => model.Question, new { #rows = "5", #cols = "35" })</td>
<td>#Html.ValidationMessageFor(model => model.Question)</td>
</tr>
</table>
<br />
<input type="submit" value="Send Enquiry" style="padding: 5px 10px;" />
</fieldset>
}
My view model:
namespace ThePines.ViewModels
{
public class EnquiryForm
{
[Required(ErrorMessage = "* Please enter a first name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "* Please enter a last name")]
public string LastName { get; set; }
[Required(ErrorMessage = "* Please enter an email address")]
[EmailAddress(ErrorMessage = "* Please enter a valid email address")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "* Please enter a country")]
public string Country { get; set; }
[Required(ErrorMessage = "* Please enter a party size")]
public int PartySize { get; set; }
[Required(ErrorMessage = "* Please enter an arrival day")]
public int ArrivalDay { get; set; }
[Required(ErrorMessage = "* Please enter an arrival month")]
public int ArrivalMonth { get; set; }
[Required(ErrorMessage = "* Please enter an arrival year")]
public int ArrivalYear { get; set; }
[Required(ErrorMessage = "* Please enter a departure day")]
public int DepartureDay { get; set; }
[Required(ErrorMessage = "* Please enter a departure month")]
public int DepartureMonth { get; set; }
[Required(ErrorMessage = "* Please enter a departure year")]
public int DepartureYear { get; set; }
[Required(ErrorMessage = "* Please enter a question")]
public string Question { get; set; }
}
}
My controller:
using ThePines.ViewModels;
namespace ThePines.Controllers
{
public class EnquiriesController : Controller
{
//
// GET: /Enquiries/
public ActionResult Index()
{
ViewBag.PartySizes = Enumerable.Range(1, 8);
ViewBag.ArrivalDay = Enumerable.Range(1, 31);
ViewBag.ArrivalMonth = Enumerable.Range(1, 12);
ViewBag.ArrivalYear = Enumerable.Range(DateTime.Now.Year, 3);
ViewBag.DepartureDay = Enumerable.Range(1, 31);
ViewBag.DepartureMonth = Enumerable.Range(1, 12);
ViewBag.DepartureYear = Enumerable.Range(DateTime.Now.Year, 3);
return View();
}
// POST: /Enquiries/
[HttpPost]
public ActionResult Index(FormCollection enquiryForm)
{
ViewBag.PartySizes = Enumerable.Range(1, 8);
ViewBag.ArrivalDay = Enumerable.Range(1, 31);
ViewBag.ArrivalMonth = Enumerable.Range(1, 12);
ViewBag.ArrivalYear = Enumerable.Range(DateTime.Now.Year, 3);
ViewBag.DepartureDay = Enumerable.Range(1, 31);
ViewBag.DepartureMonth = Enumerable.Range(1, 12);
ViewBag.DepartureYear = Enumerable.Range(DateTime.Now.Year, 3);
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
message.Append("Name: " + enquiryForm["FirstName"] + " " + enquiryForm["LastName"] + "\n");
message.Append("Email Address: " + enquiryForm["EmailAddress"] + "\n");
message.Append("Country: " + enquiryForm["Country"] + "\n");
message.Append("Party Size: " + enquiryForm["PartySize"] + "\n");
message.Append("Arrival Date: " + enquiryForm["ArrivalDate"] + "/" + enquiryForm["ArrivalMonth"] + "/" + enquiryForm["ArrivalYear"] + "\n");
message.Append("Departure Date: " + enquiryForm["DepartureDate"] + "/" + enquiryForm["DepartureMonth"] + "/" + enquiryForm["DepartureYear"] + "\n");
message.Append("Questions: " + enquiryForm["Questions"]);
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(ConfigurationManager.AppSettings["SendMailSmtp"]);
mail.From = new MailAddress(ConfigurationManager.AppSettings["SendMailFrom"]);
mail.To.Add(ConfigurationManager.AppSettings["SendMailTo"]);
mail.Subject = "The Pines Enquiry";
mail.ReplyToList.Add(enquiryForm["EmailAddress"]);
mail.Body = message.ToString();
smtpServer.Send(mail);
}
return View(enquiryForm);
}
}
}
you have added parameter of action FormCollection, you need to pass ViewModel object so that it checks the Model State, currently you are posting FormCollection instead of ViewModel In your action, so your ViewModel is not posted, do like this:
[HttpPost]
public ActionResult Index(EnquiryForm enquiryForm)
{
if(ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
message.Append("Name: " + enquiryForm.FirstName + " " + enquiryForm.LastName + "\n");
message.Append("Email Address: " + enquiryForm.EmailAddress + "\n");
message.Append("Country: " + enquiryForm.Country + "\n");
message.Append("Party Size: " + enquiryForm.PartySize + "\n");
message.Append("Arrival Date: " + enquiryForm.ArrivalDate + "/" + enquiryForm.ArrivalMonth + "/" + enquiryForm.ArrivalYear + "\n");
message.Append("Departure Date: " + enquiryForm.DepartureDate + "/" + enquiryForm.DepartureMonth + "/" + enquiryForm.DepartureYear + "\n");
message.Append("Questions: " + enquiryForm.Questions);
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(ConfigurationManager.AppSettings["SendMailSmtp"]);
mail.From = new MailAddress(ConfigurationManager.AppSettings["SendMailFrom"]);
mail.To.Add(ConfigurationManager.AppSettings["SendMailTo"]);
mail.Subject = "The Pines Enquiry";
mail.ReplyToList.Add(enquiryForm.EmailAddress);
mail.Body = message.ToString();
smtpServer.Send(mail);
}
return View(enquiryForm);
}
Currently you are doing this:
[HttpPost]
public ActionResult Index(FormCollection enquiryForm)
{
}
or if you want to read posted data from FormCollection you can do like this in action:
[HttpPost]
public ActionResult Index(EnquiryForm enquiryFormModel,FormCollection enquiryFormCollection)
{
}

Categories

Resources