I'm building a fairly standard razor/c# page for an internal website. Its basically a wrapper around a query that provides valid arguments for a db query.
The page is generating an error in Asp_Web_?????.cshtml when built. For the life of me I cannot find the error. Included below is the source of the page
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "ABC Floor Limits";
}
<hgroup class="title">
<h1>#Page.Title.</h1>
<h2>Adjust.</h2>
</hgroup>
#{
var DbCustom = Database.Open("Online_Ctrack6_Custom");
var DbCustLogs = Database.Open("Online_CustLogs");
int vehicleId = -1;
string currentAction;
if(IsPost)
{
vehicleId = Request.Form["vehicleId"].AsInt();
string applianceName = Request.Form["applianceName"];
int floorHours = Request.Form["hours"].AsInt();
DateTime? dateToParse;
DateTime dateTaken;
string result = "";
if (string.IsNullOrEmpty(Request.Form["dateTaken"]) == false)
{
var dtValue = new DateTime();
if (DateTime.TryParse(Request.Form["dateTaken"], out dtValue))
{
dateToParse = dtValue;
}
else
{
dateToParse = null;
}
}
else
{
dateToParse = null;
}
currentAction = Request.Form["action"];
if (currentAction == "updateHours")
{
try
{
dateTaken = (DateTime)dateToParse;
result = doProcessHoursForm(DbCustLogs, vehicleId, applianceName, dateTaken, floorHours);
}
catch (InvalidDataException ex)
{
#:<div class="error">#ex.Message</div>
}
catch (ArgumentNullException ex)
{
#:<div class="error">#ex.ParamName cannot be null.<br />#ex.Message #ex.ParamName</div>
}
finally
{
#:<div class="result">#result</div>
}
}
}
List<SelectListItem> listVehicles = null;
try
{
listVehicles = doCreateVehicleList(DbCustom, vehicleId);
}
catch (Exception ex)
{
#:<div class="error">#ex.Message<br />#ex.InnerException.Message</div>
}
string floorSql = "SELECT [NodeId],[PrimaryPropertyValue],[ID],[PumpADurationSec],[PumpAFloorSec],[PumpAFloorDate],[PumpATotalSec],[PumpBDurationSec],[PumpBFloorSec],[PumpBFloorDate],[PumpBTotalSec],[VacuumDurationSec],[VacuumFloorSec],[VacuumFloorDate],[VacuumTotalSec] FROM [Ctrack6_Custom].[dbo].[vwVeoliaRunningTotals] ORDER BY [Id]";
var floorGrid = new WebGrid(source: DbCustom.Query(floorSql), canPage: false, ajaxUpdateContainerId: "floorGrid");
}
<div class="section">
<h3>Current Floor Values</h3>
<p>This table lists the current floor values for ABC . The values are saved internally as a number of seconds.</p>
#floorGrid.GetHtml(
tableStyle: "VeoliaFloorTable",
headerStyle: "columnHead",
alternatingRowStyle: "altRow",
columns: floorGrid.Columns(
floorGrid.Column(columnName: "NodeId", header: #Functions.Sorter("NodeId", "Node Id", floorGrid)),
floorGrid.Column(columnName: "Id", header: #Functions.Sorter("Id", "Vehicle", floorGrid)),
floorGrid.Column(columnName: "PumpAFloorSec", header: #Functions.Sorter("PumpAFloorSec", "Pump A Floor Sec", floorGrid), style: "alignRight"),
floorGrid.Column(columnName: "PumpAFloorDate", header: #Functions.Sorter("PumpAFloorDate", "Pump A Floor Date", floorGrid), style: "nowrap"),
floorGrid.Column(columnName: "PumpBFloorSec", header: #Functions.Sorter("PumpBFloorSec", "Pump B Floor Sec", floorGrid), style: "alignRight"),
floorGrid.Column(columnName: "PumpBFloorDate", header: #Functions.Sorter("PumpBFloorDate", "Pump B Floor Date", floorGrid), style: "nowrap"),
floorGrid.Column(columnName: "VacuumFloorSec", header: #Functions.Sorter("VacuumFloorSec", "Vacuum Floor Sec", floorGrid), style: "alignRight"),
floorGrid.Column(columnName: "VacuumFloorDate", header: #Functions.Sorter("VacuumFloorDate", "Vacuum Floor Date", floorGrid), style: "nowrap")
)
);
</div>
<div class="section">
<h3>Update Floor Limits</h3>
<p>This form allows you to update the floor limit specified for an appliance mounted on a vehicle.</p>
<form method="post">
<input type="hidden" name="username" value="#WebSecurity.CurrentUserName" />
<input type="hidden" name="action" value="updateHours" />
<label for="selectVehicleControl">Choose Geozone:</label>
#Html.DropDownList("vehicleId", listVehicles)
<label for="selectApplianceControl">Choose Appliance:</label>
<select name="applianceName" id="selectApplianceControl">
<option value="-1">Choose an Appliance</option>
<option value="Pump A">Pump A</option>
<option value="Pump B">Pump B</option>
<option value="Vacuum">Vacuum</option>
</select>
<label for="inputHoursText">Hour Reading:</label>
<input name="hours" type="number" id="inputHoursText" min="0" max="9999999" size="7" required="required" />
<span style="font-size:small">This will be converted into seconds</span>
<br />
<label for="dateTakenControl">Date Taken:</label>
<input name="dateTaken" class="datetimefield" type="datetime" id="dateTakenControl" maxlength="19" required="required" />
<br />
<input type="submit" value="Update Hour Reading" />
</form>
</div>
#{
public string doProcessHoursForm(Database DbCustLogs, int vehicleId, string applianceName, DateTime dateTaken, int floorHours)
{
int floorSeconds = floorHours * 3600;
string sqlHoursUpdate = "exec sp_Veolia_update_floor_limit #0, #1, #2, #3";
if(vehicleId != null && applianceName != null && dateTaken != null && floorSeconds != null)
{
var result = DbCustLogs.Execute(sqlHoursUpdate, vehicleId, applianceName, dateTaken.ToString("yyyy-MM-dd HH:mm:ss"), floorSeconds);
if ( result != 1)
{
throw new InvalidDataException("Operation should only affect one record");
}
else
{
return result + " row(s) changed";
}
}
else
{
string nullArg = "";
if (vehicleId == null) { nullArg += "vehicleId,";}
if (applianceName == null) { nullArg += "applianceName,"; }
if (dateTaken == null) { nullArg += "dateTaken,"; }
if (floorSeconds == null) { nullArg += "floorSeconds,"; }
if (nullArg.Length > 1) { nullArg = nullArg.TrimEnd(','); }
throw new ArgumentNullException(nullArg, "Argument cannot be null");
}
return "An error ocured";
}
public List<SelectListItem> doCreateVehicleList(Database db, int vehicleId)
{
var sqlVehicles = "SELECT NodeId, Id as VehicleName FROM vwVeoliaNodes ORDER BY Id";
List<SelectListItem> listTemp = new List<SelectListItem>();
listTemp.Add(new SelectListItem
{
Text = "Select a Vehicle",
Value = "-1",
Selected = false
});
try
{
foreach (var item in db.Query(sqlVehicles))
{
if (item.NodeId == vehicleId)
{
listTemp.Add(new SelectListItem
{
Text = item.VehicleName,
Value = item.NodeId.ToString(),
Selected = true
});
}
else
{
listTemp.Add(new SelectListItem
{
Text = item.VehicleName,
Value = item.NodeId.ToString(),
Selected = false
});
}
}
}
catch (Exception ex)
{
throw new Exception("Exception occurred building Vehicle List", ex);
}
return listTemp;
}
}
The error details follow:
Error No: 1
Error Message: } expected
File: c:\Users\Lukem\AppData\Local\Temp\Temporary ASP.NET Files\root\53d555f7\b262e6b6\App_Web_abcfloor.cshtml.cdcab7d2.abupdzvs.0.cs
Line: 760
The error in the tempfile is the EndContext reference:
BeginContext("~/VeoliaFloor.cshtml", 5970, 36, true);
WriteLiteral(" />\r\n </form>\r\n </div>\r\n\r\n");
EndContext("~/VeoliaFloor.cshtml", 5970, 36, true);
I've installed a colour matching {} tool to help. There seem to be no problems in the page, only when compiled to the temp file. This is driving me mad.
It is because you are missing the #functions keyword in the section where you are declaring the methods.
Related
I'm using PagedList library for pagination and also have ordering and filtering. The problem is that after submit of order/filter request the pagination resets to page 1 but I have to keep it at current page? How can this be achieved? I also don't know if this is the right behavior but I was told to it is.
This is my controller:
public class ProductSearchBlockController : BlockController<ProductSearchBlock>
{
private readonly IRepository<Products> _productsRepository;
public ProductSearchBlockController(IRepository<Products> productsRepository)
{
_productsRepository = productsRepository;
}
public override ActionResult Index(ProductSearchBlock currentBlock)
{
if (Session[SessionConstants.Products] == null)
{
Session[SessionConstants.Products] = _productsRepository.All();
}
var sessionProducts = Session[SessionConstants.Products] as IEnumerable<Products>;
var searchString = Request.QueryString.Get(RequestQueryConstants.SearchString);
var orderBy = Request.QueryString.Get(RequestQueryConstants.OrderBy);
var pageNumber = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (string.IsNullOrEmpty(orderBy))
{
orderBy = "default";
}
if (!string.IsNullOrEmpty(searchString))
{
var result = sessionProducts.Where(p => p.OrganizaitonId.Contains(searchString) ||
p.ProductName.Contains(searchString)).ToList();
Session[SessionConstants.ProductsResult] = result;
}
else
{
var result = sessionProducts.ToList();
Session[SessionConstants.ProductsResult] = result;
}
var productsResult = Session[SessionConstants.ProductsResult] as List<Products>;
productsResult = TableDisplayHelper.OrderedProducts(orderBy, productsResult);
var viewModel = new ProductSearchBlockViewModel();
viewModel.Products = productsResult.ToPagedList(int.Parse(pageNumber), 2);
viewModel.PageNumber = int.Parse(pageNumber);
viewModel.OrderBy = orderBy;
viewModel.FilterBy = searchString;
viewModel.Options = currentBlock.Options;
return PartialView(viewModel);
}
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if (searchString != null)
{
page = 1;
}
int pageNumber = page ?? 1;
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, pageNumber.ToString());
return Redirect(finalUrl);
}
This is the view:
<div class="block esproductsearchblock col-lg-12 col-md-12 col-sm-12 col-xs-12 ">
<div class="es-product-search-block es-product-search-block-index b-spacing-default fonts-regular template-base block-wrapper">
<div class="template-search-block wrapper-fullsize" data-is-pagination-enabled="True" style="opacity: 1; pointer-events: auto;">
<section class="product-search wrapper-940" style="opacity: 1; pointer-events: auto;">
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", FormMethod.Get))
{
<span>Order By</span>
<select id="orderBySelect" name="orderBy" aria-hidden="true">
#if (Model.Options != null)
{
foreach (var item in Model.Options)
{
if (Model.OrderBy == item.Trim().ToLower())
{
<option value="#item" selected>#item</option>
}
else
{
<option value="#item">#item</option>
}
}
}
</select>
<div class="search-field bottom-aligned-m">
<input id="search-field-inputid" class="search-field-input" name="searchString" placeholder="Search" value="#Model.FilterBy">
<i class="fa fa-close"></i>
</div>
<button class="btn">Submit Search</button>
<a class="btn" href="/ProductSearchBlock/GetTableData">Clear Search</a>
<div id="distribution-status-filter" data-distribution-status-filter-id="251" data-distributon-status-options="Phased out,Mature,Active"></div>
}
</section>
<div class="search-results-table wrapper-940">
<section class="results">
<div class="products">
#foreach (var product in Model.Products)
{
<div class="product product-data">
<div class="title-container">
<p class="product-name">#product.ProductName</p>
</div>
<div class="group">
<p class="indication">#product.OrganizaitonId</p>
</div>
<div class="price">
<h6>Price per Unit</h6>
<p class="small-text bold">
#product.Price <span class="product-price__currency-marker">€</span>
</p>
</div>
#using (Html.BeginForm("AddToCart", "ProductSearchBlock", FormMethod.Get))
{
<div class="float-container">
<div class="float-child">
<h6>Quantity</h6>
<input min="1" style="width:50%" type="number" name="quantity" value="0">
<input hidden type="number" name="id" value="#product.Id">
</div>
<div class="float-child">
<button class="cart-btn primary-btn">Add</button>
</div>
</div>
}
</div>}
</div>
#Html.PagedListPager(Model.Products, page => Url.Action("GetTableData", "ProductSearchBlock",
new
{
page,
orderBy = Model.OrderBy,
searchString = Model.FilterBy
}),
new PagedListRenderOptions
{
ContainerDivClasses = new List<string> { "pagination" }, LiElementClasses = new List<string> { "paginationSpan" }
});
</section>
</div>
</div>
</div>
Found a solution maybe there is a better version but current one works.
Added parameter pageNumber to form and changed form to post:
#using (Html.BeginForm("GetTableData", "ProductSearchBlock", new { pageNumber=Model.PageNumber}, FormMethod.Post))
In controller get the current page number and check if exists set page to current page
public ActionResult GetTableData(string searchString, string orderBy, int? page)
{
var currentPage = Request.QueryString.Get(RequestQueryConstants.PageNumber);
if (searchString == null && orderBy == null)
{
return Redirect(PageHelper.CurrentPageUrl());
}
if(currentPage != null)
{
page = int.Parse(currentPage);
}
var orderByQuery = UriUtil.AddQueryString(PageHelper.CurrentPageUrl(), RequestQueryConstants.OrderBy, orderBy.ToString());
var SearchStringQuery = UriUtil.AddQueryString(orderByQuery, RequestQueryConstants.SearchString, searchString);
var finalUrl = UriUtil.AddQueryString(SearchStringQuery, RequestQueryConstants.PageNumber, page.ToString());
return Redirect(finalUrl);
}
I am working on update form, my scenario is I don't want to update new image I just want to update only other data then submit when I submit the form "image URL" shows the null value not show the old path of the image.i have tried this code which I am sharing you kindly tell me how to resolve this issue.
Just give the hint of code then I will resolve this.
Model
public class ProductViewModel{
public string ImageUrl { get; set; }
[NotMapped]
public HttpPostedFileBase imageUpload { get; set; }
public ProductViewModel()
{
ImageUrl = "~/Scripts/imageloading/image.jpg";
}
}
c#
public ActionResult AddOrEditProducts(ProductViewModel prod)
{
Product pro = new Product();
ProductDetail p_spec = new ProductDetail();
var result = new jsonMessage();
try
{
List<ProductType> PTlist = _IproductType.PTList();
ViewBag.Ptlist = new SelectList(PTlist, "PType_ID", "P_Name");
//Product Color List
List<P_Color> pColorList = _IProductColor.PColorlist();
ViewBag.pColor_List = new SelectList(pColorList, "C_ID", "C_Name_OR_Code");
List<P_Size> pSizeList = _ISize.pSizeList();
ViewBag.pSizeLists = new SelectList(pSizeList, "S_ID", "S_Size");
if (prod.imageUpload != null) // shows null here
{
string filename = Path.GetFileName(prod.imageUpload.FileName);
string _filename = DateTime.Now.ToString("yymmssff") + filename;
string extension = Path.GetExtension(prod.imageUpload.FileName);
prod.ImageUrl= "~/upload/" + _filename;
if (extension.ToLower() == ".jpeg" || extension.ToLower() == ".jpg" || extension.ToLower() == ".png")
{
if (prod.imageUpload.ContentLength <= 1000000)
{
prod.imageUpload.SaveAs(Path.Combine(Server.MapPath("~/upload/"), _filename));
p_spec = new ProductDetail();
p_spec.ProductID = prod.ProductID;
p_spec.OS = prod.OS.Trim();
p_spec.DualSim = prod.DualSim.Trim();
p_spec.Camera = prod.Camera.Trim();
p_spec.TouchScreen = prod.TouchScreen.Trim();
p_spec.ScreenSize = prod.ScreenSize.Trim();
p_spec.ProcessorType = prod.ProcessorType.Trim();
p_spec.RAM = prod.RAM.Trim();
p_spec.InternalMemory = prod.InternalMemory.Trim();
p_spec.Wifi = prod.Wifi.Trim();
p_spec.BatteryLife = prod.BatteryLife.Trim();
p_spec.Other = prod.Other.Trim();
p_spec.PDescription = prod.PDescription.Trim();
p_spec.Model = prod.Model.Trim();
p_spec.Condition = prod.Condition.Trim();
p_spec.Discount = prod.Discount;
p_spec.ImageUrl = prod.ImageUrl;
}
else
ViewBag.sizemsg = "Size Limit accessed ";
}
else
ViewBag.fileformat = "File is not Format is not Correct";
pro = new Product();
pro.ProductID = prod.ProductID;
pro.PName = prod.PName.Trim();
pro.ManificturedPrice = prod.ManificturedPrice;
pro.P_SizeID = prod.P_SizeID;
pro.P_Color_ID = prod.P_Color_ID;
pro.PType_ID = prod.PType_ID;
pro.UnitWeight = prod.UnitWeight;
pro.UnitInStock = prod.UnitInStock;
}
if (prod.ProductID == 0)
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message= "Product has been saved success..";
result.Status = true;
ModelState.Clear();
}
else
{
_IProducts.AddOrEditProducts(pro, p_spec);
result.Message = "Product Update Successfully";
result.Status = true;
ModelState.Clear();
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
result.Message = "We are unable to process your request at this time. Please try again later.";
result.Status = false;
}
}
return RedirectToAction("ProductsList");
}
View
<div id="tabimage" class="tab-pane">
<h3 class="mgtp-15 mgbt-xs-20"> Images</h3>
<div class="vd_panel-menu">
<input type="submit" value="Save Changes" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="btnSave" />
<button type="reset" value="Cancel" class="btn vd_btn vd_bg-blue btn-icon btn-sm save-btn fa fa-save" id="" />
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-lg-3 file_upload_label"> <span title="" data-toggle="tooltip" class="label-tooltip" data-original-title="Format JPG, GIF, PNG. Filesize 8.00 MB max."> Add a new image to this product </span> </label>
<div class="col-lg-9">
<div class="col-lg-5">
<span class="btn vd_btn vd_bg-green fileinput-button">
<i class="glyphicon glyphicon-plus"></i> <span>Add files...</span>
<input type="file" name="imageUpload" multiple id="imageUpload" onchange="ShowimahePreview(this,document.getElementById('previewImage'))" />
</span>
</div>
<div class="col-lg-4">
<img src="#Url.Content(Model.ImageUrl)" alt="Alternate Text" height="150" weight="" id="previewImage" />
</div>
</div>
</div>
</div>
</div>
I have two inputs that I need to validate against each other. They are a minimum and maximum. Here is the part of my view defining them.
<div class="form-group">
<label asp-for="MinTubes" class="control-label"></label>
<input asp-for="MinTubes" class="form-control" />
<span asp-validation-for="MinTubes" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MaxTubes" class="control-label"></label>
<input asp-for="MaxTubes" class="form-control" />
<span asp-validation-for="MaxTubes" class="text-danger"></span>
</div>
And here are the properties that they are mapped to:
[Display(Name = "Min Tubes")]
[MinToValidation("MaxTubes")]
public int MinTubes { get; set; }
[Display(Name = "Max Tubes")]
[MaxToValidation("MinTubes")]
public int MaxTubes { get; set; }
This results in <input type='number'> elements with labels and validation messages.
I have created two custom validation attributes to work with them. I'll only post the MaxToValidationAttribute class, as the other one is functionally identical.
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using System;
using System.ComponentModel.DataAnnotations;
namespace CCM_Util.CustomAttributes
{
public class MaxToValidationAttribute : ValidationAttribute, IClientModelValidator
{
public MaxToValidationAttribute(string min)
: base("{0} must be greater than or equal to {1}")
{
Min = min;
}
public string Min { get; set; }
public string FormatErrorMessage(string name, string minName)
{
return string.Format(ErrorMessageString, name, minName);
}
protected override ValidationResult
IsValid(object firstValue, ValidationContext validationContext)
{
var firstComparable = firstValue as IComparable;
var secondComparable = GetSecondComparable(validationContext);
if (firstComparable != null && secondComparable != null)
{
if (firstComparable.CompareTo(secondComparable) < 0)
{
object obj = validationContext.ObjectInstance;
var thing = obj.GetType().GetProperty(Min);
var displayName = (DisplayAttribute)Attribute.GetCustomAttribute(thing, typeof(DisplayAttribute));
return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName, displayName.GetName()));
}
}
return ValidationResult.Success;
}
protected IComparable GetSecondComparable(
ValidationContext validationContext)
{
var propertyInfo = validationContext
.ObjectType
.GetProperty(Min);
if (propertyInfo != null)
{
var secondValue = propertyInfo.GetValue(
validationContext.ObjectInstance, null);
return secondValue as IComparable;
}
return null;
}
public void AddValidation(ClientModelValidationContext context)
{
context.Attributes.Add("data-val-min", Min);
context.Attributes.Add("data-val-ismax", "true");
}
}
}
Then, in Default.js, I have the following function being run as part of my document.ready function.
function minMaxValidate() {
$("input[data-val-ismin='true']").each(function (i, ele) {
$(ele).change(function () {
var maxName = $(this).attr("data-val-max");
var minName = $(this).attr("name");
var minValue = parseFloat($(this).val());
var max = $("input[data-val-ismax='true'][name='" + maxName + "']");
var maxValue = max.val();
if (maxValue == "") { return }
maxValue = parseFloat(maxValue);
var validationMessage = $("span[data-valmsg-for='" + $(this).attr("name") + "']");
if (minValue > maxValue) {
validationMessage.html(minName + " must not be greater than " + maxName);
makeError(validationMessage);
}
else {
validationMessage.html("");
makeValid(validationMessage);
}
});
});
$("input[data-val-ismax='true']").each(function (i, ele) {
$(ele).change(function () {
var minName = $(this).attr("data-val-min");
var maxName = $(this).attr("name");
var maxValue = parseFloat($(this).val());
var min = $("input[data-val-ismin='true'][name='" + minName + "']");
var minValue = min.val();
if (minValue == "") { return }
minValue = parseFloat(minValue);
var validationMessage = $("span[data-valmsg-for='" + $(this).attr("name") + "']");
if (minValue > maxValue) {
validationMessage.html(maxName + " must not be less than " + minName);
makeError(validationMessage);
}
else {
validationMessage.html("");
makeValid(validationMessage);
}
});
});
}
The makeError and makeValid functions essentially just change the class of validationMessage to field-validation-error and field-validation-valid respectively, and they manage the submit handler.
I know that this type of validation setup works, because I am using it elsewhere without trouble.
I have stepped through the change handlers and they are working just as they should. However, after the error message shows up and the code exits, it disappears again. My guess is that .NET's default number input validation is taking over, and since the inputs are both valid numbers, it removes the error message.
Is there any way to disable .NET's default validation on number type inputs so that I can handle it myself and not have external black box code messing with my stuff?
Thanks.
EDIT:
Here are the view and Default.js files in their entirety, just in case.
#model Coils.CoilParts.Distributor
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#{
ViewData["Title"] = ViewData["ProgramName"];
}
<h1>Create</h1>
<h4>Distributor</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Material" class="control-label"></label>
#Html.DropDownListFor(m => m.Material.Key, ((IEnumerable<SelectListItem>)ViewData["Materials"]))
<span asp-validation-for="Material" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Type" class="control-label"></label>
<input asp-for="Type" class="form-control" />
<span asp-validation-for="Type" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MinTubes" class="control-label"></label>
<input asp-for="MinTubes" class="form-control" />
<span asp-validation-for="MinTubes" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MaxTubes" class="control-label"></label>
<input asp-for="MaxTubes" class="form-control" />
<span asp-validation-for="MaxTubes" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="InletSize" class="control-label"></label>
<input asp-for="InletSize" class="form-control" />
<span asp-validation-for="InletSize" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PartNumber" class="control-label"></label>
<input asp-for="PartNumber" class="form-control" />
<span asp-validation-for="PartNumber" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Price" class="control-label"></label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Weight" class="control-label"></label>
<input asp-for="Weight" class="form-control" />
<span asp-validation-for="Weight" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
$(document).ready(function () {
breadcrumbs();
measurementsValidate();
minMaxValidate();
});
var cgi_menus = {
'act': "the Accounting Menu",
'adm': "the Administation Menu",
'car': "the Corrective Action Request Menu",
'cprA': "the A+Pro Menu",
'cprC': "the CoilPro Menu",
'crm': "the Customer Relations Menu",
'dms': "the Document Management Menu",
'eng': "the Engineering Menu",
'etb': "the Engineering Toolbox Menu",
'ldc': "the Refrigeration Load Simulator Menu",
'mgt': "the Management Menu",
'prd': "the Production Menu",
'pur': "the Purchasing Menu",
'qcd': "the Quality Control Menu",
'rpt': "the Report Menu",
'sls': "the Sales Menu",
'sup': "the Administrator's Menu",
'usr': "the User Management Menu",
'utl': "the Utility Menu",
};
function breadcrumbs() {
var tab = {};
localStorage[curURL] = curProgram;
if (sessionStorage.tab) {
tab = JSON.parse(sessionStorage.tab);
}
else {
tab.cur_url = "";
tab.prev_url = "";
tab.history = [];
}
// handle coming from an existing Perl CGI menu
if (!tab.prev_url && document.referrer) {
var menu_info = document.referrer.match(/cgi-s[\\/](\w{3})[\\/]menu(\w?)\.cgi/);
var referrer = new URL(document.referrer);
if (menu_info && referrer.hostname === document.location.hostname) {
tab.cur_url = document.referrer;
var cgi_area = menu_info[1];
if (cgi_area == "cpr") { cgi_area += menu_info[2]; }
localStorage[tab.cur_url] = cgi_menus[cgi_area];
}
}
tab.time = Date.now();
tab.history.push(tab.prev_url);
tab.prev_url = tab.cur_url;
tab.cur_url = curURL;
if (tab.prev_url == tab.cur_url) {
tab.prev_url = tab.history.pop();
}
else if (tab.cur_url == tab.history[tab.history.length - 1]) {
tab.history.pop();
tab.prev_url = tab.history.pop();
}
if (tab.prev_url) {
$("#breadcrumbs").css("display", "inline-block");
$("#breadcrumbs").attr("href", tab.prev_url);
$("#breadcrumbs").html("< Back to " + localStorage[tab.prev_url]);
}
sessionStorage.tab = JSON.stringify(tab);
}
function minMaxValidate() {
$("input[data-val-ismin='true']").each(function (i, ele) {
$(ele).change(function () {
var maxName = $(this).attr("data-val-max");
var minName = $(this).attr("name");
var minValue = parseFloat($(this).val());
var max = $("input[data-val-ismax='true'][name='" + maxName + "']");
var maxValue = max.val();
if (maxValue == "") { return }
maxValue = parseFloat(maxValue);
var validationMessage = $("span[data-valmsg-for='" + $(this).attr("name") + "']");
if (minValue > maxValue) {
validationMessage.html(minName + " must not be greater than " + maxName);
makeError(validationMessage);
}
else {
validationMessage.html("");
makeValid(validationMessage);
}
});
});
$("input[data-val-ismax='true']").each(function (i, ele) {
$(ele).change(function () {
var minName = $(this).attr("data-val-min");
var maxName = $(this).attr("name");
var maxValue = parseFloat($(this).val());
var min = $("input[data-val-ismin='true'][name='" + minName + "']");
var minValue = min.val();
if (minValue == "") { return }
minValue = parseFloat(minValue);
var validationMessage = $("span[data-valmsg-for='" + $(this).attr("name") + "']");
if (minValue > maxValue) {
validationMessage.html(maxName + " must not be less than " + minName);
makeError(validationMessage);
}
else {
validationMessage.html("");
makeValid(validationMessage);
}
});
});
}
function measurementsValidate() {
$("input[data-val-measurement='true']").each(function (i, ele) {
var enforceUnits = $(ele).attr("data-val-units");
var units = "";
var hasMax = $(ele).attr("data-val-max");
var max = 0;
var hasMin = $(ele).attr("data-val-min");
var min = 0;
var value = $(ele).val();
var validationRegex = /[0-9/.]+ [a-z./\^0-9*()]+/i;
var name = $("label[for='" + $(ele).attr("name") + "']").html();
var validationMessage = $("span[data-valmsg-for='" + $(ele).attr("name") + "']");
if (typeof (enforceUnits) !== undefined && typeof (enforceUnits) !== false) {
enforceUnits = true;
units = $(ele).attr("data-val-units");
if (hasMax != null && hasMax != false) {
hasMax = true;
max = $(ele).attr("data-val-max");
}
if (hasMin != null && hasMin != false) {
hasMin = true;
min = $(ele).attr("data-val-min");
}
$(ele).change(function () {
var value = $(this).val(); // don't know why this has to be re-evaluated, but it does
if (!value.match(validationRegex)) {
validationMessage.html(name + " must be a valid Measurement. (example: 12 in)");
makeError(validationMessage);
}
else {
$.post("/Validations/Measurements", { EnforceUnits: enforceUnits, Units: units, HasMax: hasMax, Max: max, HasMin: hasMin, Min: min, Value: value })
.done(function (result) {
if (result == "true") {
validationMessage.html("");
makeValid(validationMessage);
}
else {
validationMessage.html(name + result);
makeError(validationMessage);
}
})
.fail(function () {
validationMessage.html("");
makeValid(validationMessage);
});
}
});
}
else {
$(ele).change(function () {
if (!value.match(validationRegex)) {
validationMessage.html(name + " must be a valid Measurement. (example: 12 in)");
makeError(validationMessage);
}
else {
validationMessage.html("");
makeValid(validationMessage);
}
});
}
});
}
function makeError(ele) {
$(ele).removeClass("field-validation-valid");
$(ele).addClass("field-validation-error");
$(ele).closest("form").unbind("submit");
$(ele).closest("form").submit(function () { return false });
}
function makeValid(ele) {
$(ele).removeClass("field-validation-error");
$(ele).addClass("field-validation-valid");
$(ele).closest("form").unbind("submit");
$(ele).closest("form").submit(checkFormValidation);
}
function checkFormValidation() {
if ($(this).find(".field-validation-error")[0]) {
return false;
}
return true;
}
EDIT 2:
Here's a GIF of what is happening: https://i.imgur.com/eAiqxQJ.mp4
As is so often the case, the solution is "If you can't beat them, join them".
Instead of disabling jQuery validation on the elements that I am custom handling, the solution is just to lean into the jQuery validation library and use it the proper way. Everything remains the same on the .NET side, but the minMaxValidate() function becomes this:
function minMaxValidate() {
$.validator.addMethod("maxTo", function (value, element, param) {
var $element = $(element), $min;
if (typeof (param) === "string") {
$min = $(param);
} else {
$min = $("input[name='" + $element.attr("data-val-min") + "']");
}
if (this.settings.onfocusout) {
$min.off(".validate-maxTo").on("blur.validate-maxTo", function () {
$element.valid();
});
}
return parseInt(value) >= parseInt($min.val());
}, "Max must not be less than min");
$("input[data-val-ismax]").each(function (i, ele) {
$(ele).rules('add', { maxTo: true });
});
$.validator.addMethod("minTo", function (value, element, param) {
var $element = $(element), $max;
if (typeof (param) === "string") {
$max = $(param);
} else {
$max = $("input[name='" + $element.attr("data-val-max") + "']");
}
if (this.settings.onfocusout) {
$max.off(".validate-minTo").on("blur.validate-minTo", function () {
$element.valid();
});
}
return parseInt(value) <= parseInt($max.val());
}, "Min must not be greater than max");
$("input[data-val-ismin]").each(function (i, ele) {
$(ele).rules('add', { minTo: true });
});
}
This adds methods and rules for the normal jQuery validation to run itself.
It does exactly what I want. Thanks to This post for help.
Why is the property DEPARTMENTID not inserting into the database on create, I am using Dropdownlist
see the code below, this all my code i need your idea to correct my code.
Controller
// GET: /Budget/Create
public ActionResult Create()
{
var name = User.Identity.GetUserName();
var userroles = _roleDataContext.USERROLEs.Where(u => u.USERNAME.ToLower().Trim() == name.ToLower().Trim() && u.ROLE.Trim() == "6");
var rolegroup = from u in userroles.ToList()
join rg in _roleDataContext.ROLEGROUPs.ToList()
on u.ROLEID equals rg.ROLEID
select rg;
var usergroup = (from rg in rolegroup.ToList()
join ug in _roleDataContext.USERGROUPs.ToList()
on rg.GROUPID equals ug.GROUPID
select ug).OrderBy(i => i.DEPTCODE);
var listSelectitem = usergroup.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.DEPTCODE.Length > 20 ? #group.DEPTCODE.Substring(0, 20) : #group.DEPTCODE,
Value = #group.DEPTCODE
}).ToList();
var firstOrDefault = usergroup.FirstOrDefault();
if (firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(listSelectitem, "Value", "Text", firstOrDefault.DEPTCODE);
}
return View();
}
// POST: /Budget/Create
[HttpPost]
public ActionResult Create(BudgetViewModel model , int month = 1, int year = 2017)
{
// TODO: Add insert logic here
model.DATETIME = DateTime.Now;
BudgetDb.insert(model);
return RedirectToAction("Index");
}
View
#model WarehouseRtoRSystem.Models.BudgetViewModel
#{
ViewBag.Title = "Create";
}
<style>
.col-md-10 {
clear: both;
padding-left: 0px !important;
}
.col-md-2 {
text-align: left !important;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Budget</h2>
<hr />
#Html.ValidationSummary(true)
<label>Month </label>
<select id="month" name="month">
#{ string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; }
#for (var i = 0; i < 12; i++)
{
var m = i + 1;
if (Convert.ToInt32(ViewBag.month) == m)
{
<option value=#m selected>#Months[i]</option>
}
else
{
<option value=#m>#Months[i]</option>
}
}
</select>
<label>YEAR</label>
<select id="year" name="year">
#for (var c = 0; c < 1000; c++)
{
var yr = c + 2017;
if (Convert.ToInt32(ViewBag.year) == yr)
{
<option value=#yr selected>
#yr
</option>
}
else
{
<option value=#yr> #yr</option>
}
}
</select>
<br />
<br />
<div class="form-group">
<label> LIST OF YOUR DEPARTMENT</label>
<span class="">#Html.DropDownList("DEPARTMENTID", (SelectList)ViewBag.DeptList, new { #class = "form-control" })</span>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BUDGET, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBox("ShowBudget", null, new { #class = "form-control" })
#Html.HiddenFor(model => model.BUDGET, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BUDGET)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
<br />
<br />
<br />
</div>
}
<div>
#Html.ActionLink("Back to List", "Index", null, new { #class ="btn btn-primary"})
</div>
<script>
$(document).ready(function () {
$("#ShowBudget").change(function () {
var value = parseFloat($(this).val());
$("#BUDGET").val(value); //assign the current value to BUDGET field
if (!isNaN(value)) {
var result = value.toLocaleString(
"en-US", // use a string like 'en-US' to override browser locale
{ minimumFractionDigits: 2 }
);
$(this).val(result);
}
})
})
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model
namespace WarehouseRtoRSystem.Models
{
public class BudgetModel
{
public int MONTH { get; set; }
public int YEAR { get; set; }
public string DEPARTMENTID { get; set; }
public DateTime DATETIME { get; set; }
//[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public double BUDGET { get; set; }
public string GROUPID { get; set; }
}
public class BudgetViewModel : BudgetModel
{
public string DEPARTMENTNAME { get; set; }
public double EXPENCES { get; set; }
public double BALANCE { get; set; }
}
public class BudgetContext
{
private readonly OracleCommand cmd = new OracleCommand();
private OracleConnection Conn = new OracleConnection();
private readonly OracleConnModel ORCONN = new OracleConnModel();
public List<BudgetViewModel> List()
{
var Departments = new List<BudgetViewModel>();
///SQL QUERY
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
cmd.CommandText = "SELECT * From PH.SYSTEMBUDGET";
cmd.CommandType = CommandType.Text;
var dr = cmd.ExecuteReader();
while (dr.Read())
{
var Dept = new BudgetViewModel();
Dept.MONTH = dr.GetInt32(0);
Dept.YEAR = dr.GetInt32(1);
Dept.DEPARTMENTID = dr.GetString(2);
Dept.DATETIME = dr.GetDateTime(3);
Dept.BUDGET = dr.GetDouble(4);
Dept.GROUPID = dr.IsDBNull(5) ? "" : dr.GetString(5);
Departments.Add(Dept);
}
}
finally
{
Conn.Close();
}
return Departments;
}
public string insert(BudgetModel model)
{
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
//var date = new DateTime();
// date = DateTime.Now;
var query = "INSERT into PH.SYSTEMBUDGET(";
query += "MONTH,";
query += "YEAR,";
query += "DEPARTMENTID,";
query += "DATETIME,";
query += "BUDGET,";
query += "GROUPID";
query += ")";
query += "VALUES(";
query += "'" + model.MONTH + "',";
query += "'" + model.YEAR + "',";
query += "'" + model.DEPARTMENTID + "',";
query += "TO_DATE('" + DateTime.Now + "','MM/DD/YYYY HH:MI:SS AM'),";
query += "'"+ model.BUDGET + "'," ;
query += "'" + model.GROUPID + "'";
query += ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
finally
{
Conn.Close();
}
return "Seccessfully inserted";
}
}
}
The error resides in the following code in your controller, whereby you are setting the Value of the SelectListItem to be the DEPTCODE description instead of the ID of the DEPTCODE record
Here is your code:
var listSelectitem = usergroup.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.DEPTCODE.Length > 20 ? #group.DEPTCODE.Substring(0, 20) : #group.DEPTCODE,
Value = #group.DEPTCODE
}).ToList();
The issue is here:
Value = #group.DEPTCODE
Now apologies for not re-creating the code exactly in the controller but the DEPTCODE models were not available, so I improvised slightly.
Here is my Create Controller:
[HttpGet]
public ActionResult Create()
{
List<DeptCode> _depts = new List<DeptCode>();
_depts.Add(new DeptCode { Id = 0, Description = "IT"});
_depts.Add(new DeptCode { Id = 1, Description = "Customer Services" });
_depts.Add(new DeptCode { Id = 2, Description = "Warehouse" });
var _listSelectItem = _depts.Select(#group => new SelectListItem
{
Selected = true,
Text = #group.Description,
Value = #group.Id.ToString()
}).ToList();
var firstOrDefault = _listSelectItem.FirstOrDefault();
if(firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text);
}
return View();
}
I have created my SelectListItem with the Value of the Id of the record, because in your code, you were binding ViewBag.DeptList with a SelectList whereby the dataValueField (Source) property was "Value".:
ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text);
So in my example I have selected a Warehouse department (again I made this value up for the sake of my model), and pressed Create.:
As you can see, this is now bound to model.DEPARTMENTID:
I have added my code here if you want to see how it works:
https://github.com/garfbradaz/StackOverFlowAnswers/tree/master/ASP.NET%20MVC/DropDownListNotWorking/SOAnswer-44879268
I'm having trouble returning my partial view to my controller. I was able to successfully do this once already, but it seems I'm having trouble doing it twice. Error is at the end of the code. Here's my workflow:
Controller name:
public class PatientMergeController : Controller
Page load, return view:
public ActionResult Index()
{
return View();
}
View returned is Index.cshtml:
#using ThisController = myNameSpace.Web.App.Controllers.PatientMerge.PatientMergeController
#model IEnumerable<myNameSpace.Repository.Model.PatientMerge>
#Scripts.Render(myNameSpace.Web.App.BundleConfig.GetVirtualPathForScript(myNameSpace.Web.App.BundleConfig.Scripts.PatientMerge))
#using System.Web.Helpers;
<div id="">
<h2>
Patient Merge
</h2>
<div class="container">
<div class="searchOneWrp">
<fieldset>
<legend><strong>Patient One Search</strong></legend>
First Name: <input type="text" id="fnamePone" />
Last Name: <input type="text" id="lnamePone" />
D.O.B.: <input type="text" id="dobPone" />
<button class="patient_look_up_button" id="btnPOneSearch" name="btnPOneSearch" type="submit" onclick="SearchOne()"
title="Search">
Search
</button>
</fieldset>
<div id="grdPatientOneSearch">
#{Html.RenderPartial("PatientOneSearch", Model);}
</div>
<div id="grdPatientOneOrderWrp">
#{Html.RenderPartial("PatientOneOrderDetails", Model);}
</div>
<div id="grdPatientOneRxWrp">
</div>
<div id="grdPatientOneNotesWrp">
</div>
</div>
<div class="searchTwoWrp">
<fieldset>
<legend><strong>Patient Two Search</strong></legend>
First Name: <input type="text" id="fnamePtwo" />
Last Name: <input type="text" id="lnamePtwo" />
D.O.B.: <input type="text" id="dobPtwo" />
<button class="patient_look_up_button" id="btnPTwoSearch" name="btnPTwoSearch" type="submit" onclick="SearchTwo()"
title="Search">
Search
</button>
</fieldset>
<div id="grdPatientTwoSearch">
#{Html.RenderPartial("PatientTwoSearch", Model);}
</div>
<div id="grdPatientTwoOrderWrp">
</div>
<div id="grdPatientTwoRxWrp">
</div>
<div id="grdPatientTwoNotesWrp">
</div>
</div>
</div>
</div>
This loads some search textboxes. When a user performs a search, they click a search button. The search button executes this JS:
function SearchOne() {
var fname = $("#fnamePone").val();
var lname = $("#lnamePone").val();
var dob = $("#dobPone").val();
var url = "/PatientMerge/PatientSearch";
//post to server, expect partial view to be returned as html, update page
$.post(url, { 'fname': fname, 'lname': lname, 'dob': dob, pat_number: 1 })
.done(function (response) {
$("#grdPatientOneSearch").html(response);
});
}
The controller method PatientSearch is called:
public PartialViewResult PatientSearch(string fname, string lname, string dob, int pat_number)
{
try
{
var target = new PatientRepository();
var result = target.GetPatient(fname, lname, dob, "", "", "");
List<myNameSpace.Repository.Model.PatientMerge> patientList = new List<myNameSpace.Repository.Model.PatientMerge>();
for (int i = 0; i < result.Count; i++)
{
myNameSpace.Repository.Model.PatientMerge patient = new myNameSpace.Repository.Model.PatientMerge();
patient.pat_id = result[i].PatientId;
patient.fname = result[i].FirstName;
patient.lname = result[i].LastName;
patient.phone_no = result[i].Phone;
patient.birth_date = result[i].DateOfBirth;
patient.AgeYears = result[i].Age;
patient.gender_cd = result[i].Gender;
patient.addr1 = result[i].Address1;
patient.addr2 = result[i].Address2;
patient.city = result[i].City;
patient.state_cd = result[i].State;
patientList.Add(patient);
}
if (pat_number == 1)
{
//perform patient one search query and pone view return
return PartialView("PatientOneSearch", patientList);
}
else
{
//perform patient two search query and pone view return
return PartialView("PatientTwoSearch", patientList);
}
}
catch (Exception ex)
{
myNameSpace.Repository.Model.PatientMerge patient = new myNameSpace.Repository.Model.PatientMerge();
List<myNameSpace.Repository.Model.PatientMerge> patientList = new List<myNameSpace.Repository.Model.PatientMerge>();
patient.fname = "Error";
patientList.Add(patient);
Logger.Log.Error(ex.Message + ex.StackTrace + ex.InnerException);
//return Json(new { error = ex.Message }, JsonRequestBehavior.AllowGet);
if (pat_number == 1)
{
//perform patient one search query and pone view return
return PartialView("PatientOneSearch", null);
}
else
{
//perform patient two search query and pone view return
return PartialView("PatientTwoSearch", null);
}
}
}
This controller returns the partial view PatientOneSearch.cshtml
#using ThisController = myNameSpace.Web.App.Controllers.PatientMerge.PatientMergeController
#model IEnumerable<myNameSpace.Repository.Model.PatientMerge>
#{
myNameSpace.Repository.Model.PatientMerge pat = new myNameSpace.Repository.Model.PatientMerge();
}
#if (Model != null)
{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 20, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "grdContent");
grid.Pager(WebGridPagerModes.NextPrevious);
<div id="grdContent">
#grid.GetHtml(tableStyle: "webgrid PatientOneGrid",
headerStyle: "table-header",
alternatingRowStyle: "alt POneSearch",
selectedRowStyle: "select POneSearch",
rowStyle: "POneSearch",
columns: grid.Columns(
grid.Column("pat_id", "Patient ID"),
grid.Column("pat_status_cn", "Status"),
grid.Column("fname", "First Name"),
grid.Column("lname", "Last Name"),
grid.Column("birth_date", "DOB"),
grid.Column("AgeYears", "Age"),
grid.Column("gender_cd", "Gender"),
grid.Column("phone_no", "Phone"),
grid.Column("addr1", "Address 1"),
grid.Column("addr2", "Address 2"),
grid.Column("city", "City"),
grid.Column("state_cd", "State")
)
)
</div>
}
else
{
<label>No records found.</label>
}
The view above populates a web grid. The below JS is waiting for row clicks.
<script>
$('.POneSearch').on('click', function () {
SearchOneGetDetails(this);
});
</script>
Row clicked, execute this function:
function SearchOneGetDetails(obj) {
var url = '/PatientMerge/OrderSearch';
var patid = $(obj).find('td:first').text();
$.post(url, { 'pat_id': patid , 'pat_number': 1 })
.done(function (response) {
$("#grdPatientOneOrderWrp").html(response);
});
}
The controller method OrderSearch is called:
public PartialViewResult OrderSearch(int pat_id, int pat_number)
{
try
{
var target = new PatientRepository();
var result = target.GetPatientOrders(pat_id, "36500");
List<myNameSpace.Repository.Model.PatientMergeOrder> patientList = new List<myNameSpace.Repository.Model.PatientMergeOrder>();
for (int i = 0; i < result.Count; i++)
{
myNameSpace.Repository.Model.PatientMergeOrder patient = new myNameSpace.Repository.Model.PatientMergeOrder();
patient.DrugName = result[i].DrugName;
patient.InvoiceNBR = result[i].InvoiceNumber;
patient.LineStatus = result[i].LineStatusDescr;
patient.OrderDate = result[i].OrderDate.ToString();
patient.OrderNum = result[i].ParentOrderNo.ToString();
patient.PrimInsur = result[i].PrimaryInsurerName;
patient.SeconInsur = result[i].SecondaryInsurerName;
patient.ShipDate = result[i].ShipDate.ToString();
patient.StorePlusID = result[i].StoreId.ToString();
patient.TrackCode = result[i].TrackingCode;
patientList.Add(patient);
}
if (pat_number == 1)
{
//perform patient one search query and pone view return
return PartialView("PatientOneOrderDetails", patientList);
}
else
{
//perform patient two search query and pone view return
return PartialView("PatientTwoOrderDetails", patientList);
}
}
catch (Exception ex)
{
Logger.Log.Error(ex.Message + ex.StackTrace + ex.InnerException);
if (pat_number == 1)
{
//perform patient one search query and pone view return
return PartialView("PatientOneOrderDetails", null);
}
else
{
//perform patient two search query and pone view return
return PartialView("PatientTwoOrderDetails", null);
}
}
}
HERE IS WHERE THE ISSUE OCCURS. I expect the partial view "PatientOneOrderDetails" to be returned. My code runs and enters the if statement if(pat_number == 1) and gets to the line where the partial return is executed, but never enters into that partial file. I do not think MVC can find my partial, but I cannot understand why.
My View structure is:
Views/PatientMerge/...
Index.cshtml
PatientOneSearch.cshtml
PatientOneOrderDetails.cshtml
And here is the code for the expected view return:
#using ThisController = myNameSpace.Web.App.Controllers.PatientMerge.PatientMergeController
#model IEnumerable<myNameSpace.Repository.Model.PatientMerge>
#{
myNameSpace.Repository.Model.PatientMerge pat = new myNameSpace.Repository.Model.PatientMerge();
}
#if (Model != null)
{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 20, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "grdOrderContentOne");
grid.Pager(WebGridPagerModes.NextPrevious);
<div id="grdOrderContentOne">
#grid.GetHtml(tableStyle: "webgrid",
headerStyle: "table-header",
alternatingRowStyle: "alt",
selectedRowStyle: "select",
columns: grid.Columns(
grid.Column("add_date", "Order Date"),
grid.Column("order_id", "Order #"),
grid.Column("StorePlusID", "Order Store"),
grid.Column("LineStatus", "Line Status"),
grid.Column("invoice_nbr", "Script"),
grid.Column("drug_name", "Drug Name"),
grid.Column("PrimaryInsurance", "Primary Insurance"),
grid.Column("SecondaryInsurance", "Secondary Insurance"),
grid.Column("ship_date", "Ship Date"),
grid.Column("tracking_code", "UPS Tracking #")
)
)
</div>
}
else
{
<label>No records found.</label>
}
The model definition is wrong you expect a myNameSpace.Repository.Model.PatientMerge in the partial and you are sending a myNameSpace.Repository.Model.PatientMergeOrder