ASP.NET MVC Master Detail Entry Form - asp.net-mvc

I’m trying to implement an order entry form using ASP.NET MVC but facing a lot of difficulties. All the samples that I found are related to viewing master detail forms, and none for adding or editing.
Suppose I have two tables: Order and OrderLines that are related to each others with one-to-many relationship. In the main view I had a “New” button when clicked it should show a new order view composed of the order fields, a grid that shows the order lines, and a “Save” button that when clicked will persist the whole order along with its lines into a database. The grid should have three buttons: “Add Line”, “Edit Line”, and “Delete Line”. When the “Add Line” is clicked a new view should be shown that allows the user to add the line to the order view grid lines –at this stage the database is not affected-. When the user clicks “Edit Line” a view will be shown that allows the user to edit the selected line and when done update the order grid lines.
The most difficult problems are:
How to pass the order and its lines collection between the order view and the order line views?
How to update the order view based on changes in the order line view?
And how to persist changes between views without the database being involved?
Is there a concrete example that shows how to implement this using MVC?
Your help and feedback is appreciated.

Pleas have a look at my blog post on creating master detail form in asp.net mvc. it also contains demo project that you can download

Unlike WebForms, ASP.NET MVC does not try to hide the stateless nature of HTTP. To work with a complex object across multiple forms you have a couple of options:
Save the object on the server with each change so that the updated object is available using only an id
Use jquery to populate the order line form and save details to the main form
I usually go with the client side option myself, with the main form having hidden fields for the data that will be edited in the subform. You may find the server side option easier though - if you really don't want to involve the database you can keep your partially updated object in the session.

Step 1: Create view model
public class OrderVM
{
public string OrderNo { get; set; }
public DateTime OrderDate { get; set; }
public string Description { get; set; }
public List<OrderDetail> OrderDetails {get;set;}
}
Step 2: Add javascript for add order lines
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
$(function () {
$('#orderDate').datepicker({
dateFormat : 'mm-dd-yy'
});
});
$(document).ready(function () {
var orderItems = [];
//Add button click function
$('#add').click(function () {
//Check validation of order item
var isValidItem = true;
if ($('#itemName').val().trim() == '') {
isValidItem = false;
$('#itemName').siblings('span.error').css('visibility', 'visible');
}
else {
$('#itemName').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#quantity').val().trim() != '' && !isNaN($('#quantity').val().trim()))) {
isValidItem = false;
$('#quantity').siblings('span.error').css('visibility', 'visible');
}
else {
$('#quantity').siblings('span.error').css('visibility', 'hidden');
}
if (!($('#rate').val().trim() != '' && !isNaN($('#rate').val().trim()))) {
isValidItem = false;
$('#rate').siblings('span.error').css('visibility', 'visible');
}
else {
$('#rate').siblings('span.error').css('visibility', 'hidden');
}
//Add item to list if valid
if (isValidItem) {
orderItems.push({
ItemName: $('#itemName').val().trim(),
Quantity: parseInt($('#quantity').val().trim()),
Rate: parseFloat($('#rate').val().trim()),
TotalAmount: parseInt($('#quantity').val().trim()) * parseFloat($('#rate').val().trim())
});
//Clear fields
$('#itemName').val('').focus();
$('#quantity,#rate').val('');
}
//populate order items
GeneratedItemsTable();
});
//Save button click function
$('#submit').click(function () {
//validation of order
var isAllValid = true;
if (orderItems.length == 0) {
$('#orderItems').html('<span style="color:red;">Please add order items</span>');
isAllValid = false;
}
if ($('#orderNo').val().trim() == '') {
$('#orderNo').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderNo').siblings('span.error').css('visibility', 'hidden');
}
if ($('#orderDate').val().trim() == '') {
$('#orderDate').siblings('span.error').css('visibility', 'visible');
isAllValid = false;
}
else {
$('#orderDate').siblings('span.error').css('visibility', 'hidden');
}
//Save if valid
if (isAllValid) {
var data = {
OrderNo: $('#orderNo').val().trim(),
OrderDate: $('#orderDate').val().trim(),
//Sorry forgot to add Description Field
Description : $('#description').val().trim(),
OrderDetails : orderItems
}
$(this).val('Please wait...');
$.ajax({
url: '/Home/SaveOrder',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
//clear form
orderItems = [];
$('#orderNo').val('');
$('#orderDate').val('');
$('#orderItems').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
error: function () {
alert('Error. Please try again.');
$('#submit').val('Save');
}
});
}
});
//function for show added items in table
function GeneratedItemsTable() {
if (orderItems.length > 0) {
var $table = $('<table/>');
$table.append('<thead><tr><th>Item</th><th>Quantity</th><th>Rate</th><th>Total</th></tr></thead>');
var $tbody = $('<tbody/>');
$.each(orderItems, function (i, val) {
var $row = $('<tr/>');
$row.append($('<td/>').html(val.ItemName));
$row.append($('<td/>').html(val.Quantity));
$row.append($('<td/>').html(val.Rate));
$row.append($('<td/>').html(val.TotalAmount));
$tbody.append($row);
});
$table.append($tbody);
$('#orderItems').html($table);
}
}
});
</script>
Step 3: Create an action for save data
[HttpPost]
public JsonResult SaveOrder(OrderVM O)
{
bool status = false;
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
foreach (var i in O.OrderDetails)
{
//
// i.TotalAmount =
order.OrderDetails.Add(i);
}
dc.Orders.Add(order);
dc.SaveChanges();
status = true;
}
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status} };
}
you can download source code and video tutorial

You could try Telericks free MVC grid control...
http://demos.telerik.com/aspnet-mvc/grid/hierarchyserverside

Just off the top of my head (a kind of brain dump)...
You could have a main grid part of the form. This would be full view loaded from an action (either with an order number or not depending on loading an existing one or not).
When clicking an event (new or edit) this could open a partial view in a "lightbox" style. This would then pass back a json object back to the main form.
The passed json object would then be rendered using templating to the bottom of the table (for a new one) or update an existing record. This could also be saved back to the server in the same ajax call. Or just update the client side and need the user to click a save button.
An isDirty flag will be needed so any changes set it to true and the when the browser tries to leave or close etc. then you can prompt the user to save or not.
Hope this helps.
edit
Not tried this but could be interesting with the none db aspect of your question click

Step 3: Create an action for save data.
[HttpPost]
public JsonResult SaveOrder(OrderVM O)
{
bool status = false;
if (ModelState.IsValid)
{
using (ManageMobileStoreWebContext dc = new ManageMobileStoreWebContext())
{
//Random rnd = new Random();
//OrderID = rnd.Next(),
Order order = new Order { OrderNo = O.OrderNo, OrderDate = O.OrderDate, Description = O.Description };
foreach (var i in O.OrderDetails)
{
if(order.OrderDetails == null)
{
order.OrderDetails = new List<OrderDetail>();
}
// i.TotalAmount =
order.OrderDetails.Add(i);
//dc.OrderDetails.Add(i);
}
dc.Orders.Add(order);
dc.SaveChanges();
status = true;
}
}
else
{
status = false;
}
return new JsonResult { Data = new { status = status } };
}

Related

.Net 6 Razor View Not Updating after Post

I am passing a complex model to a Razor View. The data in the model is used in a for-each loop in the view to display a list of products that are for sale in bootstrap cards. There are no forms on the view.
On the left side of the page are list elements that contain nested list elements. These represent product categories. When the user selects a category, I pass the product category to an action method in the controller as an integer. This will build a new model based on the selected category. The new model is then passed back to the view.
At this point, I want to display the categories that are in the category that the user selected. But, the view is not updating even though the model is now different.
I have been reading about this issue, and one forum post I read suggested that this is by design. I read somewhere that in order to achieve what I need to achieve, I have to clear the model state. But I cannot clear the model state because I am not passing the model back to the controller, and you can only pass the model back to the controller by reconstructing the model to be passed in an ajax call for example. I spent all day yesterday trying to get ajax to work and every time I executed the post, the model was populated in the JavaScript function and null or empty in the controller.
Is there another way to force the view to update upon sending a new model to the view? Does anyone have any suggestions?
<script type="text/javascript">
function AddSubCategory(elem) {
event.stopPropagation();
var e = document.querySelectorAll(".products");
e.forEach(box => {
box.remove();
});
var categoryId= $(elem).data('sub-id');
console.log(`Id: ${categoryId}`);
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
if (request != null) {
var url = `/Products/GetProductsByCategory?categoryId=${categoryId}`;
request.open("POST", url, false);
};
//request.onreadystatechange = function () {
// if (request.readyState == 4 && request.status == 200) {
// }
//};
request.send();
// model = JSON.stringify(model);
// console.log(model);
// $.ajax({
// type: "Post",
// url: '#Url.Action("GetProductsByCategory", "Products")',
// data: JSON.stringify({"categoryId": categoryId}),
// contentType: 'charset=utf-8;application/json',
// cache: false,
// complete: function (data) {
// }
//});
}
// Load all products
public async Task<IActionResult> Index()
{
ReadCartIDFromCookie();
string SubDomain = GetSubDomain(HttpContext);
var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain);
var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();
ViewBag.host = SubDomain;
ViewBag.productCategoryLookup = productCategoryLookup;
return View("Index", allProducts);
}
//Load filtered list of products
[HttpPost]
public async Task<IActionResult> GetProductsByCategory(int categoryId = -1)
{
ReadCartIDFromCookie();
string SubDomain = GetSubDomain(HttpContext);
var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain, categoryId);
var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();
ViewBag.host = SubDomain;
ViewBag.productCategoryLookup = productCategoryLookup;
return View("Index", allProducts);
}
I was able to resolve my issue thanks to this post: https://stackoverflow.com/a/66277911/1561777
I did have a bit of trouble trying to figure it out because it was not completely clear, but I could tell it was what I needed to do. I ended up utilizing a partial view for the display of my products. Here is my final code.
//My index.cshtml razor view
<div class="col" id="product"></div>//partial view will be loaded onto this div
//Javascript function that gets the chosen filter category Id
#section Scripts
{
<script type="text/javascript">
function AddSubCategory(elem) {
event.stopPropagation();
//get the id
var categoryId= $(elem).data('sub-id');
console.log(`Id: ${categoryId}`);
//call controller Products, controller action GetProductsByCategory and pass the categoryId
//The partial view will be returned and load onto the div id #product
$('#product').load(`/Products/GetProductsByCategory?categoryId=${categoryId}`);
}
//when the index view first loads, load all products (i.e. category -1)
$('#product').load(`/Products/GetProductsByCategory`);
</script>
}
public async Task<IActionResult> GetProductsByCategory(int categoryId = -1)
{
ReadCartIDFromCookie();
string SubDomain = GetSubDomain(HttpContext);
var allProducts = await _productService.GetAllProductsWithImagesAsync(SubDomain, categoryId);
var productCategoryLookup = await _productService.GetAllProductCategoryLookupAsync();
ViewBag.host = SubDomain;
ViewBag.productCategoryLookup = productCategoryLookup;
//notice that I am using PartialView method
//Returning View was including the full website (i.e. header and footer).
//_Products is my partial view. allProducts is the
//view model that is being passed to the partial view.
return PartialView("_Products", allProducts);
}
Now, everytime I select a new category, the partial view is reloaded. Also, when first loading the view, all products are displayed as expected.

Populating A Select List Dynamically MVC

I am attempting to create a cascading dropdown. My Controller looks like this to initialize the view..
public ActionResult Create()
{
var model = new RoundDetailViewModel();
model.AvailableFacilities = new SelectList(db.Facilities, "FacilityId", "Facility_Name");
model.AvailableCourses = new SelectList(Enumerable.Empty<Course>(), "CourseId", "Course_Name");
model.AvailableTeeTypes= new SelectList(Enumerable.Empty<TeeType>(), "TeeTypeId", "Name");
return View(model);
}
This will populate the first dropdown, and also create 2 empty dropdown as expected.
Now on a selection of the first dropdown I want to call an Action in my controller to populate the second dropdown. This is where I am a little foggy on the code in the action to populate the second dropdown. I want to use something like this to trigger calling the action..
$("#ddlFacility").change(function () {
var selectedFacility = $(this).val();
if (selectedFacility != null && selectedFacility != '') {
$.getJSON("#Url.Action("GetCourse")", { facility: selectedFacility }, function (courses) {
var coursesSelect = $('#ddlCourse');
coursesSelect.empty();
$.each(courses, function (index, course) {
coursesSelect.append($('<option/>', {
value: course.value,
text: course.text
}));
});
});
}
});
public ActionResult Courses(int facilityId)
{
//WHAT GOES HERE TO POPULATE SELECT LIST??
}
Need to return JsonResult and allow Get (if that is what you decide to do) Alternatively you need to make it a POST and do a POST to it.
Something like
public JsonResult GetCourses(int id)
{
var Courses= db.Courses.Where(a=>facilityId==id).ToList();
SelectList list = new SelectList(Courses,"Text", "Value");
return Json(list , JsonRequestBehavior.AllowGet);
}

ASP.NET MVC two user control

I have two user controls on the page and one of the user control has this text aread.
which is used to add a note and but when they click add note button the page reloads.
I do not want the page to reload ,i was looking for an example which this is done without
postback.
Thanks
i tired doing this using JSON , but it throws the following error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
</asp:Content>
Something like this would give you the ability to send data to an action do some logic and return a Json result then you can update your View accordingly.
Javascript Function
function AddNote(){
var d = new Date(); // IE hack to prevent caching
$.getJSON('/MyController/MyAction', { data: "hello world", Date: d.getTime() }, function(data) {
alert(data);
// call back update your view here
});
}
MyController Action
public virtual JsonResult MyAction(string data)
{
// do stuff with your data here, which right now my data equals hello world for this example
return Json("ReturnSomeObject");
}
What you want is AJAX update. There will always be a postback (unless you are satisfied with simple Javascript page update that does not save on the server), but it won't be the flashing screen effect any more.

Deleting multiple records in ASP.NET MVC using jqGrid

How can you enable multiple selection in a jqGrid, and also allow users to delete all of the selected rows using an ASP.NET MVC controller?
I have set the delete url property to my /Controller/Delete method, and this works fine if one record is selected. However, if multiple records are selected, it attempts to send a null value back to the controller where an integer id is required.
You can, but you have to write code for it:
deleteSelected: function(grid) {
if (!grid.jqGrid) {
if (console) {
console.error("'grid' argument must be a jqGrid");
}
return;
}
var ids = grid.getGridParam('selarrrow');
var count = ids.length;
if (count == 0) return;
if (confirm("Delete these " + count + " records?")) {
$.post("DeleteMultiple",
{ ids: ids },
function() { grid.trigger("reloadGrid") },
"json");
}
}
[HttpPost]
public ActionResult DeleteMultiple(IEnumerable<Guid> ids)
{
if (!Request.IsAjaxRequest())
{
// we only support this via AJAX for now.
throw new InvalidOperationException();
}
if (!ids.Any())
{
// JsonError is an internal class which works with our Ajax error handling
return JsonError(null, "Cannot delete, because no records selected.");
}
var trans = Repository.StartTransaction();
foreach (var id in ids)
{
Repository.Delete(id);
}
trans.Commit();
return Json(true);
}
I want to update this for MVC2 and jquery 1.4.2, if you want to pass array parameters to mvc2:
var ids = $("#grid").getGridParam('selarrrow');
var postData = { values: ids };
if (confirm("Delete these " + count + " records?")) {
$.ajax({
type: "POST",
traditional: true,
url: "GridDBDemoDataDeleteMultiple",
data: postData,
dataType: "json",
success: function() { $("#grid").trigger("reloadGrid") }
});
}
check http://jquery14.com/day-01/jquery-14 ajax part
thx

ASP.NET MVC: Server Validation & Keeping URL paramters when returning the view

I currently have the following code for the POST to edit a customer note.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
else
{
var _customer = _customerRepository.GetCustomer(new Customer() { CustomerID = Convert.ToInt32(note.CustomerID) });
var _notePriorities = _customerRepository.GetNotePriorities(new Paging(), new NotePriority() { NotePriorityActive = true });
IEnumerable<SelectListItem> _selectNotePriorities = from c in _notePriorities
select new SelectListItem
{
Text = c.NotePriorityName,
Value = c.NotePriorityID.ToString()
};
var viewState = new GenericViewState
{
Customer = _customer,
SelectNotePriorities = _selectNotePriorities
};
return View(viewState);
}
}
If Validation fails, I want it to render the EditNote view again but preserve the url parameters (NoteID and CustomerID) for something like this: "http://localhost:63137/Customers/EditNote/?NoteID=7&CustomerID=28"
Any ideas on how to accomplish this?
Thanks!
This action is hit by using a post. Wouldn't you want the params to come through as part of the form rather than in the url?
If you do want it, I suppose you could do a RedirectToAction to the edit GET action which contains the noteId and customerId. This would effectively make your action look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
//It's failed, so do a redirect to action. The EditNote action here would point to the original edit note url.
return RedirectToAction("EditNote", "Customers", new { id = note.CustomerID.ToString() });
}
The benefit of this is that you've removed the need to duplicate your code that gets the customer, notes and wotnot. The downside (although I can't see where it does it here) is that you're not returning validation failures.

Resources