When I am using this code as web view, it works fine, but when with developer option in Chrome I select Mobile View, FormCollection shows empty strings in the controller
VIEW (Edit updtaed)
<div class="page product-details-page deal-product-details-page">
#using (Html.BeginForm("AddProductToCart_Details", "DealProduct", new { productId = Model.Id, shoppingCartTypeId = 1 }, FormMethod.Post))
{
<div class="page-body">
#using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
{
#{
var dataDictAttributes = new ViewDataDictionary();
dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductAttributes.cshtml", Model.ProductAttributes, dataDictAttributes)
}
<!--gift card-->
#{
var dataDictGiftCard = new ViewDataDictionary();
dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
#Html.Partial("~/Views/Product/_GiftCardInfo.cshtml", Model.GiftCard, dataDictGiftCard)
}
<!--rental info-->
#{
var dataDictRental = new ViewDataDictionary();
dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
#Html.Partial("~/Views/Product/_RentalInfo.cshtml", Model, dataDictRental)
}
<!--price & add to cart-->
#{
var dataDictPrice = new ViewDataDictionary();
dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductPrice.cshtml", Model.ProductPrice, dataDictPrice)
#Html.Partial("~/Views/Product/_ProductTierPrices.cshtml", Model.TierPrices)
}
<!--wishlist, compare, email a friend-->
<!--attributes-->
#{
var item = #Model.AssociateProductAttributesList.Where(x => x.Item1 == data.Id).Select(x => x.Item2).ToList()[0];
bool isAttributes =false;
}
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<br />
#foreach (System.Collections.DictionaryEntry value in item)
{
var val = data.Id + "_" + value.Key.ToString();
isAttributes = true;
#*<div class="attributes">*#
<dl>
<dt id="product_attribute_label_19">
<label class="text-prompt">
#value.Key.ToString()
</label>
</dt>
<dd id="product_attribute_input_19" class="product_attribute_inputdiv_#val">
#Html.DropDownList("Attributes," + data.Id + "," + value.Key.ToString(), new SelectList((System.Collections.IEnumerable)value.Value, "Id", "Name"), "--- Please select ---")
</dd>
</dl>
#*</div>*#
}
<br />
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
#if (item.Count == 0)
{
#Html.Hidden("Attributes," + data.Id + ",", "0")
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
}
#if (isAttributes)
{
<a style="color: blue;" data-popup-open="popup-#data.Id" href="#">
<img id="imgdiv_#data.Id" src="~/Themes/Playground/Content/img/dealselectattribut.png" class="select-atr-img" style="width: 50%; margin-bottom: 10px;"/>
</a>
}
</div>
}
</div>
<div>
</div>
#{
var dataDictAddToCart = new ViewDataDictionary();
dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
<div class="overview" style="width:100%; margin-left:auto">
#Html.Partial("~/Views/Product/_AddToCart.cshtml", Model.AddToCart, dataDictAddToCart)
</div>
}
</div>
}
</div>
}
</div>
Controller
public ActionResult AddProductToCart_Details(int productId, int shoppingCartTypeId, FormCollection form)
{
if (_productService.IsDealProducts(productId))
{
if (!IsCompleteSelected(form))
{
return Json(new
{
success = false,
message = " Plese select all associated product attribute "
});
}
}
//more code here
}
Normal View (Web View)
Mobile View
Form in form is not allowed. This is your issue.
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 programing a CRUD application. The add and edit do not want to work properly. For Adding, it shows me the successful message that the row is added, but nothing added in reality in my database. For Edit, I have a NullReferenceException after he tries to find the reclamation by his id :
StackTrace
In Debug mode, I can see that ng-model is doing his job, the add or edit modifications are take in account.
Here is my code :
reclamations-controller.js :
(function () {
'use strict';
angular
.module('app')
.controller('ReclamationsController', function ($scope, $http) {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = "";
$scope.Reclamations.RecDescription = "";
$scope.Reclamations.RecStatus = "";
$scope.Reclamations.RecResponsible = "";
$scope.Reclamations.RecComment = "";
// Popup variables
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function (btnClicked) {
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
// Export Data to Excel file
$scope.Export = function () {
$("#tblReclamations").table2excel({
filename: "Reclamations.xls",
exportOptions: {
columns: [1, 2]
}
});
}
$scope.showAddAndEditModal = false;
$scope.showAddAndEditModalFunction = function () {
if ($scope.showAddAndEditModal == false) {
$scope.showAddAndEditModal = true;
}
else {
$scope.showAddAndEditModal = false;
}
};
$scope.showImportModal = false;
$scope.showImportModalFunction = function () {
if ($scope.showImportModal == false) {
$scope.showImportModal = true;
}
else {
$scope.showImportModal = false;
}
};
// Add new reclamation function
$scope.InsertData = function () {
var Action = document.getElementById("btnSave").getAttribute("value");
if (Action == "Submit") {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$http({
method: "post",
url: "/Data/Insert_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
})
} else {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$scope.Reclamations.RecId = document.getElementById("RecID_").value;
$http({
method: "post",
url: "/Data/Update_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
document.getElementById("btnSave").setAttribute("value", "Submit");
document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
document.getElementById("spn").innerHTML = "Add New Reclamation";
})
}
};
// Get all reclamations function
$scope.GetAllData = function () {
$http({
method: "get",
url: "/Data/Get_AllReclamation"
}).then(function (response) {
$scope.Reclamations = response.data;
}, function () {
alert("Error Occur");
})
};
// Delete function
$scope.DeleteReclamation = function (Rec) {
$http({
method: "POST",
url: "/Data/Delete_Reclamation",
datatype: "JSON",
data: JSON.stringify(Rec)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
})
};
// Update function
$scope.UpdateReclamation = function (Rec) {
document.getElementById("RecID_").value = Rec.RecId;
$scope.RecDate = new Date(Rec.RecDate);
$scope.RecTitle = Rec.RecTitle;
$scope.RecDescription = Rec.RecDescription;
$scope.RecStatus = Rec.RecStatus;
$scope.RecResponsible = Rec.RecResponsible;
$scope.RecComment = Rec.RecComment;
document.getElementById("btnSave").setAttribute("value", "Update");
document.getElementById("btnSave").style.backgroundColor = "Yellow";
document.getElementById("spn").innerHTML = "Update Reclamation Information";
};
});
})();
index.cshtml :
<p class="text-info text-center"><h3>Reclamations list</h3></p>
<div ng-app="app">
<div ng-controller="ReclamationsController" ng-init="GetAllData()" class="divList">
#*Reclamation Menu options*#
<div id="container" class="container">
<div class="row">
<input type="text" ng-model="searchFilter" placeholder="Search" />
<button ng-click="showAddAndEditModalFunction()" class="btn btn-primary a-btn-slide-
text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Add</strong></span>
</button>
<button class="btn btn-primary a-btn-slide-text" onclick="history.go(0);">
<span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
<span>
<strong>Refresh</strong>
</span>
</button>
</div>
</div>
<br /><br /><br />
#* Reclamation table *#
<table id="tblReclamations" class="tableData" width="80" border="0" cellpadding="0"
cellspacing="0">
<thead>
<tr>
<th>Reclamation ID</th>
<th>Title</th>
<th>Description</th>
<th>Status</th>
<th>Responsible</th>
<th>Comment</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Rec in Reclamations | filter: searchFilter" ng-class-odd="'odd'" ng-class-
even="'even'">
<td>{{Rec.RecId}}</td>
<td>{{Rec.RecTitle}}</td>
<td>{{Rec.RecDescription}}</td>
<td>{{Rec.RecStatus}}</td>
<td>{{Rec.RecResponsible}}</td>
<td>{{Rec.RecComment}}</td>
<td>
<button ng-click="UpdateReclamation(Rec); showAddAndEditModalFunction()"
class="btn btn-primary a-btn-slide-text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Edit</strong></span>
</button>
<a ng-click="DeleteReclamation(Rec)" class="btn btn-danger a-btn-slide-text">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span>
</a>
</td>
</tr>
</tbody>
</table>
#* Add and edit part *#
<br /><br /><br /><br />
<div ng-show="showAddAndEditModal" class="form-horizontal" role="form">
<div class="container">
<div class="row">
<h2>
<span id="spn">Add New Reclamation</span>
</h2>
</div>
<div class="row">
#*<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Date :</label>
<div class="col-md-8">
<input type="date" class="form-control" id="inputDate" placeholder="Date"
ng-model="RecDate">
</div>
</div>
</div>*#
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Title :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputTitle"
placeholder="Title" ng-model="RecTitle">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Description :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputDescription"
placeholder="Description" ng-model="RecDescription">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Status :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputStatus"
placeholder="Status" ng-model="RecStatus">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Responsible :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputResponsible"
placeholder="Responsible" ng-model="RecResponsible">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Comment :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputComment"
placeholder="Comment" ng-model="RecComment">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<input type="button" id="btnSave" class="form-control btn-space" value="Submit"
ng-click="InsertData()" />
</div>
</div>
</div>
</div>
</div>
#Html.Hidden("RecID_")
</div>
#section scripts {
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">
</script>
<script src="~/Scripts/app/controllers/reclamations-controller.js"></script>
<script src="~/Scripts/app/controllers/import-controller.js"></script>
<script>
function refreshPage() {
window.location.reload();
}
</script>
}
DataController :
public JsonResult Get_AllReclamation ()
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
List<Reclamation> Rec = Obj.Reclamations.ToList();
return Json(Rec, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Get_ReclamationById (string Id)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
int RecId = int.Parse(Id);
return Json(Obj.Reclamations.Find(RecId), JsonRequestBehavior.AllowGet);
}
}
public string Insert_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
if (ModelState.IsValid)
{
try
{
Obj.Reclamations.Add(Rec);
Obj.SaveChanges();
}
catch (DbEntityValidationException ex)
{
ErrorPrinter(ex.EntityValidationErrors);
}
catch (Exception ex)
{
Console.WriteLine("Exception not managed :");
Console.WriteLine(ex.Message);
}
}
return "Reclamation Added Successfully";
}
}
else
{
return "Reclamation Not Inserted! Try Again";
}
}
public string Update_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
Reclamation RecObj = Obj.Reclamations.Where(a => a.RecId ==
Rec.RecId).FirstOrDefault();
RecObj.RecTitle = Rec.RecTitle;
RecObj.RecDescription = Rec.RecDescription;
RecObj.RecStatus = Rec.RecStatus;
RecObj.RecResponsible = Rec.RecResponsible;
RecObj.RecComment = Rec.RecComment;
Obj.SaveChanges();
return "Reclamation Updated Successfully";
}
}
else
{
return "Reclamation Not Updated! Try Again";
}
}
Thank you !
I have been trying to create a the ability to add/edit records through the use of a modal in .net core.
I have been trying tutorials such as
https://www.youtube.com/watch?v=QmNtbnUfns8
https://www.mindstick.com/Articles/12723/crud-operation-modal-popup-uses-bootstrap-in-mvc
Neither of these are working for as they are as .net. The modal isnt showing up.
ViewClients.cshtml
#model IEnumerable<Evol.Models.Clients>
#{
ViewData["Title"] = "Clients";
Layout = "~/Views/Shared/_Layout.cshtml";
<div class="card">
<div class="card-header card-header-text card-header-rose">
<div class="card-text">
<h4 class="card-title">Clients</h4>
<p class="card-category"></p>
</div>
</div>
<div class="card-body table-responsive">
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead class="text-gray">
<tr>
<th>
#Html.DisplayNameFor(model => model.ClientName)
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(model => item.ClientName)
</td>
<td class="text-right">
<i class="material-icons">edit</i>
<button type="button" rel="tooltip" title="Remove" class="btn btn-
danger btn-link btn-sm">
<i class="material-icons">close</i>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="myModal1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h3 class="modal-title">AddEdit Employee</h3>
</div>
<div class="modal-body" id="myModalBodyDiv1">
</div>
</div>
</div>
</div>
<script>
var EditClient = function (ClientID) {
var url = "/Client/EditClient?ClientID=" + ClientID;
$("#myModalBodyDiv1").load(url, function () {
$("#myModal1").modal("show");
})
}
EditClient.cshmtl (partial view)
#model Evol.Models.Clients
<form id="myForm">
#Html.HiddenFor(m => m.ClientID)
#Html.TextBoxFor(model => model.ClientName, new { #class = "form-control", #placeholder = "Name" })
<a href="#" id="btnSubmit" class="btn btn-success btn-block">
#if (Model.ClientID > 0)
{
<span>Update</span>
}
else
{
<span>Save</span>
}
</a>
</form>
Add Client
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
$("#loaderDiv").show();
var myformdata = $("#myForm").serialize();
alert("Success")
$.ajax({
type: "POST",
url: "/Client/ViewClients",
data: myformdata,
success: function () {
$("#loaderDiv").hide();
$("#myModal1").modal("hide");
}
})
})
})
ClientContoller
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
Did You Created DbContext Class In Your Project?
CRUD Operations In ASP.NET Core Using Entity Framework Core Code First
EF Core DbContext Class Sample
below code just sample for show data and edit or add data to table.
[HttpGet]
public IActionResult AddEditCustomer(long? id)
{
CustomerViewModel model = new CustomerViewModel();
if (id.HasValue)
{
Customer customer = context.Set<Customer>().SingleOrDefault(c => c.Id == id.Value);
if (customer != null)
{
model.Id = customer.Id;
model.FirstName = customer.FirstName;
model.LastName = customer.LastName;
model.MobileNo = customer.MobileNo;
model.Email = customer.Email;
}
}
return PartialView("~/Views/Customer/_AddEditCustomer.cshtml", model);
}
[HttpPost]
public ActionResult AddEditCustomer(long? id, CustomerViewModel model)
{
try
{
if (ModelState.IsValid)
{
bool isNew = !id.HasValue;
Customer customer = isNew ? new Customer
{
AddedDate = DateTime.UtcNow
} : context.Set<Customer>().SingleOrDefault(s => s.Id == id.Value);
customer.FirstName = model.FirstName;
customer.LastName = model.LastName;
customer.MobileNo = model.MobileNo;
customer.Email = model.Email;
customer.IPAddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
customer.ModifiedDate = DateTime.UtcNow;
if (isNew)
{
context.Add(customer);
}
context.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("Index");
}
This is because you are missing the HTTP Post attribute PLEASE SEE the docs here
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-3.1
[HTTPPOST]
public IActionResult EditClient(int ClientID)
{
Clients client = new Clients();
if(ClientID > 0)
{
var user = _context.ClientTable.SingleOrDefault(x => x.ClientID == clientID);
client.ClientID = user.ClientID;
client.ClientName = user.ClientName;
}
return PartialView("EditClient", client);
}
}
I am working on load more data functionality as per my requirement I am displaying 12 records for the first time and it works fine for me but whenever I am trying to show the rest data the earlier data is getting lost and the current data is displaying.
For this purpose, I am using a list which is coming from code behind but my problem is I'd declared the List on the view which is initialized each and every time then every time it becomes null on at the time of data binding that is the reason earlier data is getting lost.
For this purpose, I can not use AJAX
Here is my View
#model List<ChangiRecommends.BAL.ViewModel.Product.ProductViewModel>
#using ChangiRecommends.BAL.ViewModel.Product;
#using ChangiRecommends.Utilities;
#{
if(ViewBag.productCount > 12)
{
}
List<ProductViewModel> productList = new List<ProductViewModel>();
if(productList.Count == 0)
{
productList = Model;
}
else
{
productList.AddRange(Model);
}
ViewBag.Title = "destination";
Layout = "~/Views/Shared/_Layout.cshtml";
var key = ViewBag.Key;
var searchingKey = ViewBag.searchingkey;
var skip = ViewBag.skip;
}
<div class="destination_pics">
<div class="row">
#if (productList.Count>0)
{
int count = 0;
foreach (var item in productList)
{
if (count == 0)
{
<div class="col-sm-8">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 0 && count <= 2)
{
if (count == 1)
{
#:<div class="col-sm-4">
}
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
if (count == 2)
{
#:</div>
<div class="clearfix"></div>
}
}
else if (count > 2 && count <= 5)
{
<div class="col-sm-4">
<div class="highlights">
<a href="#Url.Action("tourdetail", "customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="highlithsTxt"> <p><strong>$#item.OnlinePrice</strong></p> <p>#item.ProductDisplayName</p> </div>
<img class="img-fluid" src="#item.ProductImage">
</a>
</div>
</div>
}
else if (count > 5 && count <= 8)
{
<div class="col-sm-4">
<div class="card activityBox activeBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
else if (count > 8 && count < 12)
{
<div class="col-sm-4">
<div class="card activityBox">
<a href="#Url.Action("tourdetail","customer",new {key = QueryStringManager.Encrypt(item.ID)})">
<div class="dealTags">
<div class="tag-spcial">Special Offer</div>
</div>
<img class="card-img-top" src="#item.ProductImage" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">#item.ProductDisplayName</h5>
<div class="row">
<div class="col-md-4 dealPrice">
<label>From</label>
$#item.OnlinePrice <span>$30.00</span>
</div>
<div class="col-md-5 dealLocation"><label>Location</label>#item.DestinationName</div>
<div class="col-md-3 favIt"><i class="far fa-heart"></i></div>
</div>
</div>
</a>
</div>
</div>
}
count++;
}
if (ViewBag.productCount > 12)
{
skip += 12;
<div class="clearfix"></div>
<div class="loadMore"> Load More Results</div>
}
}
</div>
</div>
</div>
In this view, I'd declared a list on the top as it is initialized at every and I want to declare it as static so that the earlier data should not be lost.
Here is my controller.
public ActionResult destination(string key, string searchingkey, FilterDataViewModel model, int skip = 0)
{
TempData["HeaderColor"] = true;
if (!string.IsNullOrEmpty(key))
{
int destinationId = QueryStringManager.Decrypt(key);
var destinationInfo = _masterRepo.GetMasterDataByID(destinationId);
var productList = _websiteRepo.GetAllProductListByDestinationId(destinationId).OrderByDescending(x => x.DestinationWeightPriority).ToList();
if (model.DestinationCityID > 0)
{
productList = (from prod in productList where prod.DestinationCity == model.DestinationCityID select prod).ToList();
}
ViewBag.productCount = productList.Count();
var a = productList.Skip(skip).Take(12).ToList();
ViewBag.ProductList = productList.Skip(skip).Take(12).ToList();
var allAdbyDestination = _websiteRepo.GetAllAdvertisementList(destinationId);
ViewBag.allDestinationAd = allAdbyDestination;
ViewBag.DestinationName = destinationInfo.MasterData;
ViewBag.DestinationImages = destinationInfo.ImagePath;
var categoryID = MasterConstant.GetCategoryID(CatergoryConstant.City);
var allDestinationCity = _masterRepo.GetMasterDataByCategoryIDandXrefID(categoryID, destinationId);
ViewBag.DestinationCityList = new SelectList(allDestinationCity, "ItemID", "MasterData");
ViewBag.Key = key;
ViewBag.searchingkey = searchingkey;
ViewBag.skip = skip;
return View(a);
}
else
{
return RedirectToAction("index", "home");
}
}
As can be seen in this picture I have a list of missing dates I have not reported a time for, and when I click a date I have missed my 'Rappotera tid' gets filled in with that date.
But what I want to do is I want to remove my 'Datum' have it sole based on the check boxes that are before the date, so at at a later date can report several dates at once.
But I am stuck and I would like to get some help.
This is my view:
<script type="text/javascript" language="javascript">
$(function() {
$(function() {
$('#date').datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd",
firstDay: 1,
onSelect: function(dateText) {
$('#EndDate').datepicker('option', 'minDate', new Date(dateText));
}
});
});
});
function SetDate(dt) {
$('#date').val(dt);
}
var n = #(Model.Projects.Count);;
function AddProject() {
n++;
$.ajax({
type: "GET",
url: "#Url.Action("Project")/" + n,
dataType: "html",
success: function(data) {
$('#projects').append(data);
}
});
}
$(function() {
$('#startTime').change(function() { CalculateTime(); });
$('#endTime').change(function() { CalculateTime(); });
$('#breakTime').change(function() { CalculateTime(); });
CalculateTime();
});
function CalculateTime() {
try {
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var breakTime = $('#breakTime').val();
var startDate = new Date(2000, 1, 1, startTime.substring(0, 2), startTime.substring(3, 5), 0, 0);
var endDate = new Date(2000, 1, 1, endTime.substring(0, 2), endTime.substring(3, 5), 0, 0);
var time = endDate - startDate;
time = time / 1000 / 60 / 60;
time = time - breakTime.substring(0, 2);
time = time - (breakTime.substring(3, 5) / 60);
$('#workedHours').html(time + " timmar");
} catch (err) {
$('#workedHours').html("---");
}
}
</script>
<div class="page-container">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
#if (ViewData["posted"] != null)
{
<div class="alert alert-success">
<strong>Tidsrapporten tillagd.</strong>
</div>
}
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">missad rappoterad tid</span>
</div>
</div>
<form class="form-horizontal">
<div class="portlet-body form">
<div class="form-group">
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yy-MM-dd");
<div class="col-md-1">
<input type="checkbox" name="Date" value="Date">
#isoDate
</div>
}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#Html.ValidationSummary()
#using (Html.BeginForm("TimeReport", "Reports", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal" }))
{
#Html.Hidden("ReportId", Model.ReportId)
<div class="col-md-6">
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">Rappotera tid</span>
</div>
</div>
<div class="portlet-body form">
<div class="form-group">
<label class="col-md-3 control-label">Datum:</label>
<div class="col-md-5">
#Html.TextBox("date", Model.Date.ToShortDateString(), new {#class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Start tid:</label>
<div class="col-md-5">
#Html.TextBox("startTime", Model.Times.StartTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Slut tid:</label>
<div class="col-md-5">
#Html.TextBox("endTime", Model.Times.EndTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Rast Längd:</label>
<div class="col-md-5">
#Html.TextBox("breakTime", Model.Times.BreakTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Tid jobbad:</label>
<div class="col-md-5">
#Html.TextBox("workedHours", Model.Times.WorkedHours, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div id="projects">
#foreach (var data in Model.Projects)
{
Html.RenderPartial("Project", data, ViewData["vd"] as ViewDataDictionary);
var viewDataDictionary = ViewData["vd"] as ViewDataDictionary;
if (viewDataDictionary != null)
{
viewDataDictionary["id"] = (int)viewDataDictionary["id"] + 1;
}
}
</div>
</div>
<div class="form-actions">
<div class="col-md-offset-4 col-asdfasmd-9">
Lägg till projekt
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</div>
if (Model.ReportId.HasValue)
{
<input type="submit" value="Ta bort" name="delete" />
}
}
</div>
</div>
</div>
</div>
And this is my controller for this view:
public ActionResult TimeReport(FormCollection form, Guid? id)
{
ViewDataDictionary vd = new ViewDataDictionary
{
["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
["id"] = 1,
["showDescription"] = true
};
ViewData["vd"] = vd;
NewTimeReportModel projectData = new NewTimeReportModel();
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
return View();
}
if (id.HasValue && (form == null || form.AllKeys.Length == 0))
{
using (DatabaseLayer db = new DatabaseLayer())
{
var timeReport = db.GetTimeReport(id.Value);
projectData = new NewTimeReportModel(timeReport);
if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
else if (form == null || form.AllKeys.Length == 0)
{
LoadDefaultSettings(projectData);
}
else
{
DateTime reportDate;
if (!DateTime.TryParse(form["date"], out reportDate))
ModelState.AddModelError("Date", "Felaktikt datum");
var projectNumbers = (from x in form.AllKeys
where x.Contains("_")
select x.Substring(x.IndexOf('_'))).Distinct();
projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
projectData.Date = reportDate;
if (!projectNumbers.Any())
ModelState.AddModelError("Projekt", "Inga projekt valda...");
else
{
int emptyHours = 0;
foreach (string projectNumber in projectNumbers)
{
projectData.Projects.Add(new NewTimeReportModel.Project
{
Description = form["description" + projectNumber],
Hours = null,
ProjectId = Guid.Parse(form["project" + projectNumber])
});
string hourString = form["hours" + projectNumber];
if (string.IsNullOrEmpty(hourString))
{
emptyHours++;
projectData.Projects[projectData.Projects.Count - 1].Hours = projectData.Times.WorkedHours;
}
else
{
if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
{
ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
}
}
}
if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar stämmer ej överrens");
}
if (projectData.Projects.Where(x => x.Hours <= 0).Any())
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar måste vara större än noll");
}
if (!string.IsNullOrEmpty(form["ReportId"]))
projectData.ReportId = Guid.Parse(form["ReportId"]);
if (ModelState.IsValid)
{
projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
ViewData["posted"] = true;
projectData = new NewTimeReportModel();
LoadDefaultSettings(projectData);
}
else if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
if (missingdays.Count == 0)
{
ViewData["missingDays"] = "";
}
else
{
ViewBag.MissingDays = missingdays;
}
ViewData.Model = projectData;
return View();
}