I am trying to update the price of a Product in my MVC application, which is connected to a MySql database. I am using a javascript function that should open a textfield that is where the price can be updated. I have used this tutorial to help me out https://www.aspsnippets.com/Articles/Implement-CRUD-operations-without-using-Entity-Framework-in-ASPNet-MVC.aspx
My ProductController is the following:
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
List<Models.Product> products = new List<Models.Product>();
string constr = "server=localhost;user id=root;password=;database=accounting;persistsecurityinfo=True";
string query = "SELECT * FROM product";
using (MySql.Data.MySqlClient.MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using(MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
products.Add(new Models.Product
{
productId = Convert.ToInt32(sdr["idproduct"]),
name = Convert.ToString(sdr["name"]),
description = Convert.ToString(sdr["description"]),
cost = Convert.ToDouble(sdr["cost"]),
price = Convert.ToDouble(sdr["price"]),
stockid = Convert.ToInt32(sdr["stockid"]),
sku = Convert.ToString(sdr["sku"])
});
}
}
con.Close();
}
}
if(products.Count == 0)
{
products.Add(new Models.Product());
}
return View(products);
}
[HttpPost]
public ActionResult UpdatePrice(Models.Product product)
{
// First thing to do is to check that the User that is updating the Product is a StoreManager
// to be completed late
string query = "UPDATE product SET price=#price WHERE productId=#idproduct";
string constr = "server=localhost;user id=root;password=qn3gt6abc7;database=accounting;persistsecurityinfo=True";
using(MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Parameters.AddWithValue("#idproduct", product.productId);
cmd.Parameters.AddWithValue("#price", product.price);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
return new EmptyResult();
}
}
The Model is:
public class Product
{
public int productId { get; set; }
public string name { get; set; }
public string description { get; set; }
public double cost { get; set; }
public double price { get; set; }
public int stockid { get; set; }
public string sku { get; set; }
}
And the View is the following:
#model IEnumerable<DE_Store.Models.Product>
#{
ViewBag.Title = "Index";
}
<head>
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
</head>
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table" id="tblProducts">
<tr>
<th>
#Html.DisplayNameFor(model => model.name)
</th>
<th>
#Html.DisplayNameFor(model => model.description)
</th>
<th>
#Html.DisplayNameFor(model => model.price)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td class="Product Name">
<span>#item.name</span>
<input type="text" value="#item.name" style="display:none" />
</td>
<td class="Description">
<span>#item.description</span>
<input type="text" value="#item.description" style="display:none" />
</td>
<td class="Price">
<span>#item.price</span>
<input type="text" value="#item.price" style="display:none" />
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
<a class="Delete" href="javascript:;">Delete</a>
</td>
</tr>
}
</table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
//Edit event handler.
$("body").on("click", "#tblProducts .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
row.find(".Delete").hide();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblProducts .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Delete").show();
row.find(".Cancel").hide();
$(this).hide();
var product = {};
product.idproduct= row.find(".productId").find("span").html();
product.name = row.find(".Product Name").find("span").html();
product.price = row.find(".Price").find("span").html();
$.ajax({
type: "POST",
url: "/Product/Index",
data: '{product:' + JSON.stringify(product) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
</script>
When I run it I encounter issues with the javascript part, when I click on the Edit button nothing happens, and by inspecting the page for errors I am getting are:
Mixed content: load all resources via HTTPS to improve the security of your site.
The resources files involved are
Name Restriction Status
jquery.min.js blocked
json2.js blocked
Is there anything I can do to fix this? Any suggestion for the javascript code, or any alternative solution to update the price of the product?
Related
I am new and I need given output from the following scenario.
Required following output
|Code| Unit Name| Type| Count|
| U-1| Unit 1 name | MCQ | 25
| U-1| Unit 1 name | SEQ| 20
| U-1| Unit 1 name | Long| 50|
| U-2| Unit 2 name | MCQ | 25|
I have the Subject Dropdown when I select the Subjectname from the dropdown I want to populate the Units table with unit code, unit name and the number of questions along with their type. ( MCQ, SEQ, etc)
the classes are Subjects, Topics, and Questions.
public class Subject
{
public int Id { get; set; }
public string? SubjectText { get; set; }
//relationship to topics (one to many)
public List<Topic>? Topic { get; set; }
}
public class Topic
{
public int Id { get; set; }
public string? TopicText { get; set; }
//relationship ( one to many)
public List<Question> Question { get; set; }
//navigation back to subjects
public int SubjectId { get; set; }
public Subject Subject { get; set; }
}
public class Question
{
public int Id { get; set; }
public string? QuestionText { get; set; }
public QuestionTypes QuestionType { get; set; }
public DifficultyLevel DifficultyLevel { get; set; }
//navigation back to Topics
public int TopicId { get; set; }
public Topic? Topic { get; set; }
}
// question types and difficulty level are enums
public enum QuestionTypes
{
MCQ =1,
SEQ,
Long_Question,
Fill_In_The_Blanks
}
public enum DifficultyLevel
{
Very_Easy = 1,
Easy,
Moderate,
Hard,
Very_Hard,
}
my VM for the table is
public class TopicsWithQCountsVM
{
public int Code { get; set; }
public string? TopicText { get; set; }
public QuestionTypes QType { get; set; }
public List<int>? mcqCount { get; set; } // Multiple Choices Questions
public List<int>? seqCount { get; set; } // Short Exam Questions
public List<int>? longQCount { get; set; } // long Questions
public List<int>? FillinBlankCount { get; set; } // fill in the blanks
}
I want to display all the units along with their QuestionsTypes(MCQ,SEQ,Long) and total Count when a user select the subject from dropdownlist. The dropdown list is dynamically populated from database table called Subjects. I have a javascript function that is loading the two units from the controller and posting them back to view
controller code
public JsonResult Subject(int id)
{
var sl = _context.Subjects.Where(s => s.GradeId == id).ToList();
return new JsonResult(sl);
}
public JsonResult GetTableData(int id)
{
var query = _context.Topics
.Join(_context.Questions, Topic => Topic.Id, Question => Question.Id, (Topic, Question) => new { Topic, Question })
.Where(u => u.Topic.SubjectId == id)
.ToListAsync();
var query = _context.Topics.Where(s => s.SubjectId == id).Include(t => t.Question.Count).GroupBy(q => q.TopicText).FirstOrDefault();
var objtopiclist = new TopicsWithQCountsVM();
var query = _context.Topics.Where(s => s.SubjectId == id).ToList();
for each (var item in query)
{
var seqcount = _context.Questions.Where(q => q.TopicId == item.Id && q.QuestionType == QuestionTypes.SEQ).Count();
}
return new JsonResult(query);
}
my View is
// on change of SubjectDDL
$('#SubjectDDL').change(function() {
var id = $(this).val();
$.ajax({
type: "POST",
url: '/Dashboard/GetTableData?id=' + id,
data: '{}',
success: function(response) {
var trHTML = '';
$.each(response, function(i, item) {
trHTML += '<tr><td>' + item.code + '</td><td>' + item.topicText + '</td></tr>';
//trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#tableUnits').append(trHTML);
}
});
});
<!-- DropDown section-->
<div class="table table-hover">
<div class="row"> <h5>Please select the appropriate category</h5></div>
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-6 col-12">
<label asp-for="GradeName" class="control-label"></label>
<select id="GradeDDL" asp-for="GradeId" class="form-control" asp-items="ViewBag.Grades"> <option selected disabled>---Select Grade---</option> </select>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-12">
<label asp-for="SubjectName" class="control-label"></label>
<select id="SubjectDDL" asp-for="SubjectId" onconchange="selectedText" class="form-control"> <option selected disabled>---Select Subject---</option> </select>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-12">
<label></label>
#*<button asp-controller="dashboard" asp-action="LoadUnitsAndQuestionCount" asp-route-id="#Model.SubjectId" type="button" > Load Units </button>*#
#*<button type="submit", class="form-control btn btn-secondary"> Load Units</button>*#
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-12 col-12">
<table id="tableUnits" class="table table-bordered table-hover">
<thead> <h4>Units </h4></thead>
<tr>
<th>Unit Code</th>
<th>Unit Name</th>
<th>Type</th>
<th>Count</th>
<th>Given Question</th>
</tr>
<tr>
<td> unit1 </td>
<td> Unit Title </td>
<td> mcq </td>
<td> 25 </td>
<td> <input type="number" /> </td>
</tr>
</table>
</div>
</div>
I tried my best to do but I don't know how to write the LINQ query that meets my needs (I know my method code is full of bugs )
I want to use the VM model please help me with this problem.
thanks
I have a separate TR and inside, a TD from the rest of my table. I have some data in my model that contains a list of strings, and also a list of IDs (not sure if I need the list of IDS for this) and I would like to display on the lower Tr's td a specific part of the list, based off of the selection of a SelectListItem in the table row's td above it.. i.e. If a user select's a list item of X, I want the TD below to display "X's help description" (which like I mentioned earlier, is being stored inside a list of strings in my model)
I am not sure if I should be doing this in Razor, Javascript, or something else. Can anyone give me some tips? Below is some code.
View:
<div class="row">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Terminal</th>
<th>Command</th>
<th>Command Value</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr>
<td>#Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL, new { id = "ddlTerminalID", #class = "form-control" })</td>
<td>#Html.DropDownListFor(o => o.TerminalCommandLookupsDDL, Model.TerminalCommandLookupsDDL, new {id = "ddlCommandValue", #class = "form-control" })</td>
<td>#Html.TextBoxFor(o => o.UserEnteredTerminalCommands, new { Class = "form-control", Id = "cmdValueValue"})</td>
<td> <input id="btnSaveTerminalCommand" type="button" value="Insert" class="btn btn-primary" /> </td>
</tr>
<tr>
<td colspan="4" id="helpDescript">#Html.DisplayFor(model => model.HelpDescription)</td>
</tr>
</tbody>
</table>
</div>
</div>
VM:
public TerminalCommandVM()
{
//Terminals Drop Down List
TerminalsDDL = new List<SelectListItem>();
//Terminal Commands Drop Down List
TerminalCommandLookupsDDL = new List<SelectListItem>();
//Terminal Command Values list
TerminalCommandValues = new List<SelectListItem>();
}
public TerminalCommand TerminalCommand { get; set; }
public List<TerminalCommand> TerminalCommands { get; set; }
[Display(Name = "Terminal ID")]
public List<SelectListItem> TerminalsDDL { get; set; }
[Display(Name = "Command")]
public List<SelectListItem> TerminalCommandLookupsDDL { get; set; }
public List<SelectListItem> TerminalCommandValues { get; set; }
public string UserEnteredTerminalCommands { get; set; }
public List<string> HelpDescription { get; set; }
public List<int> HelpDescriptionID { get; set; }
}
The DisplayFor I want populated is the one with the ID = "helpDescript", and the select list item that should dictate which help descript is displayed has the ID = "ddlCommandValue".
As of now, helpDescript is displaying the entire list (obviously).
If anyone needs any other code or more information, please let me know.
Try the following. In the dropdown change event call the action to display the value and in the success function display the value in label
$("#ddlCommandValue").change(function () {
var obj = {
valueToPass: $(this).val()
};
$.ajax({
url: '/Home/GetValueToDisplayInlabel',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: JSON.stringify(obj),
cache: false,
success: function (result) {
$("#helpDescript").html(result);
},
error: function () {
alert("Error");
}
});
The following code makes up parts of an ASP.NET MVC application that I am currently working on. The index creates a table that the user can add rows by inputting the values for Tag, Server, and Frequency into a popup modal (activated by hitting the "Add" button, modal HTML code not shown). The table's initial values are currently generated by a migration from a linked SQL Database Table (created by using entity-framework).
I am trying to modify this code so that any rows added by the "Add" button will be automatically added to the linked Database Table (preferably by using entity framework). Any help would be appreciated.
Controller
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
ExampleDB _db = new ExampleDB();
public ActionResult Index()
{
var model = _db.TData.ToList();
return View(model);
}
protected override void Dispose(bool disposing)
{
if (_db != null)
{
_db.Dispose();
}
base.Dispose(disposing);
}
}
}
Classes
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
Index
#model IEnumerable<ExampleWebAppilcationTest.TableData>
#{
ViewBag.Title = "Home Page";
}
#{
ViewBag.Title = "Index";
}
<h2>Table Data</h2>
<table class="table table-bordered" id="mainTable">
<thead>
<tr>
<th></th>
<th class="thTag" scope="col">
#Html.DisplayNameFor(model => model.Tag)
</th>
<th class="thServer" scope="col">
#Html.DisplayNameFor(model => model.Server)
</th>
<th class="thFreq" scope="col">
#Html.DisplayNameFor(model => model.Frequency)
</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5">
#foreach (var item in Model)
{
<tr>
<td><input type="checkbox"/></td>
<td>
#Html.DisplayFor(modelItem => item.Tag)
</td>
<td>
#Html.DisplayFor(modelItem => item.Server)
</td>
<td>
#Html.DisplayFor(modelItem => item.Frequency)
</td>
</tr>
</tbody>
</table>
<button type="button" id="addBtn" class="btn btn-success">Add</button>
<!-- The Modals -->
<script>
var table = document.getElementById('mainTable');
// Get the modal
var addmodal = document.getElementById('addModal');
// When the user clicks the button, open the modal
btn.onclick = function () {
addmodal.style.display = "block";
}
var sbtn = document.getElementById("subBtn");
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
var objInputCheckBox = document.createElement("input");
objInputCheckBox.type = "checkbox";
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.appendChild(objInputCheckBox);
cell2.innerHTML = tag;
cell3.innerHTML = server;
cell4.innerHTML = frequency;
addmodal.style.display = "none";
}
Although you should have a Layered Architecture for your project with separare Business and DataAccess layers and controller should only be the gateway for incoming requests https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design )
This is what you can do with your current adjustment:
Controller:
namespace ExampleWebAppilcationTest.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
using (var dbContext = new ExampleDB())
{
var model = dbContext.TData.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(TableData data)
{
using (var dbContext = new ExampleDB())
{
dbContext.TData.Add(data);
dbContext.SaveChanges();
}
return RedirectToAction("Index");
}
}
}
Data Access
namespace ExampleWebAppilcationTest
{
public class ExampleDB : DbContext
{
public ExampleDB() : base(nameOrConnectionString: "Your Database Connection String") { }
public DbSet<TableData> TData { get; set; }
}
}
namespace ExampleWebAppilcationTest
{
public class TableData
{
[Key]
public String Tag { get; set; }
public String Server { get; set; }
public double Frequency { get; set; }
}
}
View
sbtn.onclick = function () {
var table = document.getElementById("mainTable");
var tag = document.getElementById("tag").value;
var server = document.getElementById("server").value;
var frequency = document.getElementById("frequency").value;
//Here fetch all data in a class
var data = { Tag: tag, Server: server, Frequency: frequency };
//make ajax call to add data
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Home")', //your action
data: data,
dataType: 'json',
success: function (result) {
//to close the popup
},
error: function (result) {
//to show error message
}
});
}
You need to add an Add method of some sort to your controller, decorated with the POST attribute. In your modal, there needs to be a form pointing to the controller's add method url. The form should contain input fields for all of your table properties. That form should be then posted via a submit button to the add method on your controller. The add method needs to take the properties of the form submitted, create a new object, then insert the new object in to the database.
I have an MVC project where I'm rendering the data using a table in my partial view as:
<table id="tblUserSettings" class="table table-bordered CmtTable">
<thead>
<tr>
<th>User Name</th>
<th>Country</th>
<th>System (s)</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#if (Model == null)
{
<tr></tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td><input type="hidden" id="usrId" value="#item.UserId" />
#item.UserName</td>
<td> <input type="hidden" id="usrCountryKey" value="#item.UserCountryKey" style="display:none"/>
#item.UserCountryName</td>
<td> <input type="hidden" id="usrSourceSystemKey" value="#item.UserSourceSystemKey" />
#item.UserSourceSystemDescription</td>
<td><a onclick='DeleteUserSettingsRow();'><i class='fa fa-times'></i> Delete</a><a onclick='EditUserSettingsPopup();'><i class='fa fa-pencil'></i> Edit</a></td>
</tr>
}
}
</tbody>
</table>
I'm going to save the values from this table into the database and need to call the AddUserSettingsaction method in controller as:
[HttpPost, Route("AddUserSettings")]
public ActionResult AddUserSettings(IEnumerable<UserSettings> request)
{
AddUserSettingsRequest apiRequest = null;
return View();
}
The model of UserSettings is as follows:
public class UserSettings
{
public UserSettings();
public string UserId { get; set; }
public string UserName { get; set; }
public string UserCountryKey { get; set; }
public string UserCountryName { get; set; }
public string UserSourceSystemKey { get; set; }
public string UserSourceSystemDescription { get; set; }
}
I need to save the data from the table (including the hidden fields) into the database using jQuery, so I have created a function and calling it as:
<button type="button" id="btnAdd" onclick="SaveUserSettings();"><i class="fa fa-save"></i> Save</button>
function SaveUserSettings()
{
debugger;
var userSettings = [];
$("table#tblUserSettings tr").each(function (i, v) {
userSettings[i] = [];
$(this).children('td').each(function (ii, vv)
{
userSettings[i][ii] = $(this).text();
});
})
alert(userSettings);
$.ajax({
url: '#Url.Action("AddUserSettings", "Admin")',
type: "POST",
contentType: "application/json;",
data: JSON.stringify(userSettings),
success : function (result)
{
//alert(result);
},
error: function (result)
{
//alert(result);
}
});
}
With the above SaveUserSettings() function, I can get the values which are not hidden, but I need to create an array which contains the hidden properties as well and can be sent with the ajax request to the controller as the parameter. How can I get the hidden fields and create an array mapped to the IEnumerable request of my controller?
Provided the javascript is in the partial view, you can set your userSettings directly against the model, for example:
var userSettings = #Html.Raw(JsonConvert.SerializeObject(Model));
This will then serialize your object into JSON and it will be passed to the browser, where you can then use it to pass it back to the server in jQuery without having to go through each row in the table.
I got a ASP.net MVC 4.0 web application which enable user to dynamically add rows to html table.
In my view:
$('.del').live('click', function () {
id--;
var rowCount = $('#options-table tr').length;
if (rowCount > 2) {
$(this).parent().parent().remove();
}
});
$('.add').live('click', function () {
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
<table class="dynatable" id="options-table" width="100%" style="text-align:center" border="1">
<tr class="prototype">
<%:Html.EditorFor(m => Model.ChillerDetails)%> //referring to the template
</tr>
<thead>
</table>
In my template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<GMIS.Models.GMISEBModels.ChillerPlantDetails>" %>
<div id="ChillerPlantDetails">
<td><%: Html.EditorFor(m => m.ChillerAge) %></td>
<td><%: Html.EditorFor(m => m.ChillerBrand) %></td>
<td><%: Html.EditorFor(m => m.ChillerCapacity) %></td>
<td><%: Html.EditorFor(m => m.ChillerRefrigerant) %></td>
<td>
<a href="#" class="add"><img src="<%= Url.Content("~/Content/Images/add.png") %>"/> <a href="#" class="del"><img src="<%= Url.Content("~/Content/Images/remove.png") %>"/>
</td>
</div>
In my Model:
public class AddHealthCheckFormModel
{
public List<ChillerPlantDetails> ChillerDetails { get; set; }
}
public class ChillerPlantDetails
{
//[Required(ErrorMessage = "Please enter Chiller Capacity.")]
[Display(Name = "Chiller Capacity")]
public string ChillerCapacity { get; set; }
//[Required(ErrorMessage = "Please enter Age of Chiller.")]
[Display(Name = "Age of Chiller")]
public string ChillerAge { get; set; }
//[Required(ErrorMessage = "Please enter Chiller Brand.")]
[Display(Name = "Chiller Brand")]
public string ChillerBrand { get; set; }
//[Required(ErrorMessage = "Please enter Chiller Refrigerant.")]
[Display(Name = "Chiller Refrigerant")]
public string ChillerRefrigerant { get; set; }
}
Now the question comes to how can I capture the data in the dynamically added rows into my controller and save into database?
You can use following View which will add new record using HTTP Post instead of Ajax.
Replacing it with Ajax.BeginForm with appropriate parameters will use the Ajax instead of plain post request.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table class="list-chiller-record">
#for (int i = 0; i < this.Model.ChillerDetails.Count; i++)
{
if (i == 0)
{
<tr class="chiller-record-template" style="display:none">
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerAge)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerBrand)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerCapacity)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerRefrigerant)</td>
</tr>
}
<tr class="chiller-record">
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerAge)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerBrand)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerCapacity)</td>
<td>#Html.EditorFor(x=>x.ChillerDetails[i].ChillerRefrigerant)</td>
</tr>
}
</table>
<br />
<input type="button" class="add-button" name="add" value="Add" />
<input type="submit" class="save-button" name="save" value="save" />
}
Add add new row:
<script type="text/javascript">
$(document).ready(function () {
var count = 2;
$('.add-button').click(function () {
count++;
var template = $('.chiller-record-template').clone()
template.find('input[type=text]').val('');
$.each(template.find('input[type=text]'), function () {
var name = $(this).attr('name');
name = name.replace('0', count - 1);
$(this).attr('name', name);
});
$('.list-chiller-record').append(template);
template.removeClass('chiller-record-template').addClass('chiller-record').show();
})
});
</script>
Your Action Could be like this:
[HttpPost]
public ActionResult AddHealthCheck(AddHealthCheckFormModel model)
{
if (ModelState.IsValid)
{
HealthCheckRepository healthCheckRepository = new HealthCheckRepository();
healthCheckRepository.save(model);
}
return this.View(model);
}
And in repository you can actually save the data in database. You can use EF or any other ORM for this.