Insert array html in C# ASP.NET - c#

I've a screen where I insert dynamic inputs with js. I work with two tables, where one I insert basic information and the other I use a FK to insert the Products.
function AddItem() {
var nItem = Number($("#nItem").val()) + 1;
$("#nItem").val(nItem);
var div = document.createElement('DIV');
div.innerHTML = '<label for="Item" class="item-label">Item:</label>';
div.innerHTML += '<input type="text" class="item-control" id="Item" name="Item" value="'+nItem+'" style="width:32px;background-color: #e9e9e9;text-align: center" readonly/>';
div.innerHTML += '<label for="Qtd" class="item-label">Qtd:</label>';
div.innerHTML += '<input type="text" class="item-control Vlr" data-val-required="Campo obrigatório" id="Qtd'+nItem+'" name="Qtd" value="0" style="width:100px;text-align: center"/>';
div.innerHTML += '<label for="Vlr" class="item-label">Valor Un:</label>';
div.innerHTML += '<input type="text" class="item-control Vlr" data-val-required="Campo obrigatório" id="Vlr'+nItem+'" name="Vlr" value="0" style="width:100px;text-align: center"/>';
div.innerHTML += '<label for="VlrItem" class="item-label">Valor Item:</label>';
div.innerHTML += '<input type="number" min="1" class="item-control VlrTotal" id="VlrItem'+nItem+'" name="VlrItem" value="0.00" style="width:100px;text-align: center;background-color: #e9e9e9" readonly/>';
div.innerHTML += '<label for="Descricao" class="item-label" >Descrição:</label>';
div.innerHTML += '<input type="text" class="item-control Validar" data-val="true" data-val-required="Campo obrigatório" id="Descricao" name="Descricao" value="" style="width:200px;text-align: center" maxlength="200"/>';
div.innerHTML += '<input type="button" value="X" class="btn btn-danger" onclick="RemoveItem(this)"/>';
document.getElementById("tabs-3").appendChild(div);
$("#Qtd").mask('999');
$(".Vlr").mask('0.000.000,00', { reverse: true });
$(".Vlr").blur(function () {
var Vlr = $("#Vlr" + nItem).val().replace(".", "");
Vlr = Vlr.replace(",", ".");
var VlrItem = parseFloat(Vlr) * parseFloat($("#Qtd" + nItem).val());
$("#VlrItem" + nItem).val(VlrItem.toFixed(2));
});
Each insertion via JS refers to a "Product". In the controller I insert data into the table "SOPA" and after I have to enter all the added products, but only the first one is being inserted. How do I get all added "Products" to be inserted? The controller looks like this:
public ActionResult Create(SopaItens obj)
{
//if (ModelState.IsValid)
//{
SOPA s = new SOPA();
s.DataSolicitacao = obj.DataSolicitacao;
s.NumSolicitacao = obj.NumSolicitacao;
s.EmitenteId = obj.EmitenteId;
s.AprovadorID = obj.AprovadorID;
s.AprovadorFinalID = obj.AprovadorFinalID;
s.CostCenterId = obj.CostCenterId;
s.DocTypeId = obj.DocTypeId;
s.NumDoc = obj.NumDoc;
s.SerieDoc = obj.SerieDoc;
s.EmitenteDoc = obj.EmitenteDoc;
s.RetISS = obj.RetISS;
s.StatesId = obj.StatesId;
s.CitiesId = obj.CitiesId;
s.AliISS = obj.AliISS;
s.RetIRRF = obj.RetIRRF;
s.AliIRRF = obj.AliIRRF;
s.RetCPP = obj.RetCPP;
s.AliCPP = obj.AliCPP;
s.VlrLiq = obj.VlrLiq;
s.Juros = obj.Juros;
s.Multa = obj.Multa;
s.Desconto = obj.Desconto;
s.VlrFinal = obj.VlrFinal;
s.DataVencimento = obj.DataVencimento;
s.DataPrevista = obj.DataPrevista;
s.ModPagId = obj.ModPagId;
db.SOPAs.Add(s);
db.SaveChanges();
try
{
ItemSOPA i = new ItemSOPA();
i.SOPAId = s.SOPAId;
i.Item = obj.Item;
i.Descricao = obj.Descricao;
i.Qtd = obj.Qtd;
i.Vlr = obj.Vlr;
i.VlrItem = obj.VlrItem;
i.VlrTotal = obj.VlrTotal;
db.ItemSOPAs.Add(i);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
Console.WriteLine(e);
}
return RedirectToAction("Index");
}

you can try making an array off the objects you are expecting, and in the controller, bind to a collection. I usually bind to an ICollection.
So your controller would look like
public ActionResult Create(ICollection<Product> objs)
{
//do controller work here
}
Then your HTML inputs for each object property would have an array index
var div = document.createElement('DIV');
div.innerHTML = '<label for="Item" class="item-label">Item:</label>';
div.innerHTML += '<input type="text" name="Product[0].ItemProperty" />';
div.innerHTML += '<label for="Qtd" class="item-label">Qtd:</label>';
div.innerHTML += '<input name="Product[0].QTDProperty" />';
//remaining innerhtml for first array item 0 here...
div.innerHTML = '<label for="Item" class="item-label">Item:</label>';
div.innerHTML += '<input type="text" name="Product[1].ItemProperty" />';
div.innerHTML += '<label for="Qtd" class="item-label">Qtd:</label>';
div.innerHTML += '<input name="Product[1].QtdProperty" />';
//remaining innerhtml here...
Ultimately you can check out this link

Related

Add #Html.DropDownList using Jquery

I have a function that insert a tr/td.
I need to insert a #Html.DropDownList but this code isn't work.
I'm developing a system using C#, bootstrap with Visual Studio.
function AddItem() {
var nItem = Number($("#nItem").val()) + 1;
$("#nItem").val(nItem);
var div = document.createElement('tr');
div.innerHTML = '<td><input type="text" class="item-control" id="Item" name="Item" value="' + nItem + '" style="width:32px;background-color: #e9e9e9;text-align: center" readonly /></td>';
div.innerHTML += '<td colspan="2"><input type="text" class="item-control Qtd" id="Qtd_' + nItem + '" name="Item" value="0" /></td>';
div.innerHTML += '<td colspan="2">#Html.DropDownList("UnMedId", null, "-", htmlAttributes: new { id = "UnMed_", Name = "Item", #class = "form-control" })</td>';
document.getElementById("itens").appendChild(div);
}
Thanks!
Thanks for all.
I use Json in controller and use a loop to create a select.
In controller:
var UnMedId2 = new SelectList(db.UnMeds, "UnMedId", "Simbolo");
ViewBag.UnMedId2 = JsonConvert.SerializeObject(UnMedId2);
In JavaScript:
var sel = '<select name="cars" id="cars">'
var UnMed = #Html.Raw(ViewData["UnMedId2"]);
for (var i = 0; i < UnMed.length; i++) {
sel += '<option value="' + UnMed[i].Value + '">' + UnMed[i].Text + '</option>';
}
sel += '</select >'
Thanks

How to update multiple div contents using C#?

In a Get Response from an API, I need to update the div's accordingly.
Below is my HTML Code
<div class="col-md-2 mb-4">
<div class="card mb-4" id="roomName_1" runat="server">
<div class="card-header text-center">
Room 1
</div>
<div class="card-body" style="background-color:#ff0000;color:white;">
<p>
<asp:Literal Text="Organizer" runat="server" ID="organiser_1" />
<br />
<label id="from_1">From</label>
-
<label id="to_1">To</label>
<br />
<asp:Literal Text="Subject" runat="server" ID="subject_1" />
</p>
</div>
</div>
</div>
There are 24 rooms like this, and for each room I have to update Organizer, From, To, Subject which I get from a GET Request.
private void GetRoom(string uri) {
var request = WebRequest.Create(uri);
string text;
var response = (HttpWebResponse)request.GetResponse();
request.ContentType = "application/json; charset=utf-8";
using(var sr = new StreamReader(response.GetResponseStream())) {
text = sr.ReadToEnd();
List<RoomConfigurationViewInfo> roomObject = JsonConvert.DeserializeObject < List<RoomConfigurationViewInfo>> (text);
foreach(var value in roomObject) {
Response.Write(value.Organizer);
Response.Write(value.Subject);
}
}
}
So, Is it possible to Update multiple Div's using C#? & if not then how can I achieve this.
Please suggest.
I found a way that you can achieve this:
At first, add ID to your first tag: <div id="rooms" runat="server" class="col-md-2 mb-4">
Now in code behind, you can try this:
private void GetRoom(string uri)
{
var request = WebRequest.Create(uri);
string text;
var response = (HttpWebResponse)request.GetResponse();
request.ContentType = "application/json; charset=utf-8";
using(var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
List<RoomConfigurationViewInfo> roomObject = JsonConvert.DeserializeObject < List<RoomConfigurationViewInfo>> (text);
rooms.InnerHtml = "";
for(int i = 0; i < roomObject.Count; i++)
{
string strOrganizer = roomObject[i].Organizer;
string strSubject = roomObject[i].Subject;
string strFrom = roomObject[i].From;
string strTo = roomObject[i].To;
rooms.InnerHtml += "<div class=\"card mb-4\">"
+ "<div class=\"card-header text-center\">"
+ "Room " + i + "";
+ "</div>"
+ "<div class=\"card-body\" style=\"background-color:#ff0000;color:white;\">"
+ "<p>"
+ "<asp:Literal Text=\"" + strOrganizer "\" runat=\"server\" ID=\"organiser_" + i + "\"/>"
+ "<br />"
+ "<label>" + strFrom + "</label>"
+ "-"
+ "<label>" + strTo + "</label>"
+ "<br />"
+ "<asp:Literal Text=\"" + strSubject + "\" runat=\"server\" ID=\"subject_" + i + "\" />"
+ "</p>"
+ "</div>"
+ "</div>";
}
}
}
I hope it helps you
It depends if you are doing it dynamically or not. If you are simply loading the page and updating the divs, pass it as a variable and then iterate through it.
Your code on your page would be something like this:
<% foreach (var myItem in g) { %>
<p>
<%= myItem.Organizer%>
<br />
<label id="from_1">From</label>
-
<label id="to_1">To</label>
<br />
<%= myItem.Subject%>
</p>
<% } %>
If you are trying to do it dynamically, the commenter above is correct and you would have to do it through jQuery/Javascript.

How to load list Data to the Dynamic data table returned from the controller?

Here is my problem:
In a view called "Select Event" user fills some data that are filled into the dynamic data table one by one record. And when he clicks next button, that data is converted to array and passed to the controller. And also it loads the next view(Select Package). In controller that data is stored in session variable.The problem is that I want that data to put again in same dynamic data table when user clicks the back button from another view called "select package". So far I've done this,
returning the stored data in session variable from contoller using json result:
public JsonResult PrevDyanamicTable()
{
List<OrderEvent> eventlist1 = new List<OrderEvent>();
Order newOrder = new Order();
if (Session["NewOrder"] != null)
{
newOrder = (Order)Session["NewOrder"];
}
eventlist1 = newOrder.OrderEvent.ToList();
OrderEvent[] eventlist = eventlist1.ToArray();
return Json(eventlist, JsonRequestBehavior.AllowGet);
}
Get ajax call:
$(document).on("click", "#btnDynmicTbl", function () {
$.ajax({
type: "GET",
url: "/OrderEvents/PrevDyanamicTable/",
//contentType: "application/json; charset = utf-8",
success: function (response) {
debugger;
window.location.href = "/OrderEvents/Create/"
var myArray = response;
$.each(myArray, function (index, OrderEvent) {
var txtEventId = OrderEvent.EventID;
var txtEventType = OrderEvent.Venue;
var txtStartingDate = OrderEvent.StartingDate;
var txtEndingDate = OrderEvent.EndingDate;
var txtStartingTime = OrderEvent.StartingTime;
var txtEndingTime = OrderEvent.EndingTime;
var txtVenue = OrderEvent.Venue;
var contactdiv = '<tr class="data-contact-Album">' +
'<td><input type="text" name="EventID" value="' + txtEventId + '" class="form-control hidden " /></td>' +
'<td><input type="text" name="EventType" value="' + txtEventType + '" disabled="disabled" class="form-control " /></td>' +
'<td><input type="text" name="StartingDate" value="' + txtStartingDate + '" disabled="disabled" class="form-control " /></td>' +
'<td><input type="text" name="EndingDate" value="' + txtEndingDate + '" disabled="disabled" class="form-control " /></td>' +
'<td><input type="text" name="StartingTime" value="' + txtStartingTime + '" disabled="disabled" class="form-control " /></td>' +
'<td><input type="text" name="EndingTime" value="' + txtEndingTime + '" disabled="disabled" class="form-control" /></td>' +
'<td><input type="text" name="Venue" value="' + txtVenue + '" disabled="disabled" class="form-control " /></td>' +
'<td><button type="button" id="btnDelete" class="deleteEvent btn btn btn-danger btn-xs">Remove</button><button type="button" id="btnUpdate" class="UpdateEvent btn btn btn-default btn-xs">Update</button></td>' +
'</tr>; ';
$('#maintable').append(contactdiv);
});
},
failure: function (response) {
alert(response.d);
}
});
});
This java script is written on the separate file inside the scripts folder. In here #btnDynmicTbl is the back button in select package view. "window.location.href ="/OrderEvent/Create/" is the view that dynamic data table loads. I have checked for the console errors and there wasn't anything.I'm new to asp.net MVC.I've managed to come this far in project thanks to the help of this stack overflow community.So How to make this work? what are the errors in this code? thanks.

Asp.Net MVC : Insert data from form collection with List of values

As you can see in picture, I have a form where I continuously add items to the table below.
When I click "Save all" button, it posts all the table values to "InsertBulk" method.
And this is what I did in my view. I am created a form within the table. Set name and values for each input field. Made the input fields hidden, displayed only text and then on clicking save all button it posts all those value to the InsertBulk method.
#model FYPPharmAssistant.Models.InventoryModel.Manufacturer
#{
ViewBag.Title = "Form";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<label>Name</label><br />
#Html.EditorFor(m => m.ManufacturerName, new { htmlAttributes = new { #class = "form-control" } }) <br />
<label>Description</label><br />
#Html.EditorFor(m => m.Description, new { htmlAttributes = new { #class = "form-control" } })
<input type="submit" id="addmore" value="add" />
}
#using (Html.BeginForm("InsertBulk", "Manufacturer"))
{
<table id="table">
<tr>
<th>
name
</th>
<th>
description
</th>
</tr>
</table>
<input type="submit" id="btnsaveall" value="Save all" />
}
<script>
$(document).on('ready', function () {
$('#addmore').on('click', function () {
var $table = $("#table");
$table.append("<tr> <td><input type='hidden' name='ManufacturerName' value='" + $('#ManufacturerName').val() + "' />" + $('#ManufacturerName').val() + "</td> <td><input type='hidden' name='Description' value='" + $('#Description').val() + "'>" + $('#Description').val() + "</td> <td><a href='javascript:void(0)' onclick='removeItem(this)'>Remove</a></td></tr>");
return false;
});
});
</script>
This is my InsertBulk method.
[HttpPost]
public void InsertBulk(FormCollection coll)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName"];
m.Description = coll["Description"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
Result :
Ans this is what I get in Result. How am I suppose to solve this ? Please help!
I also tried to count keys and loop through each in the InsertBulk method. But I think I did it all wrong.
int count = coll.Count;
if(count == 0)
{
return View("ChamForm", "Test");
}
else
{
for(int i = 0; i<count; i++)
{
Manufacturer m = new Manufacturer();
m.ManufacturerName = coll["ManufacturerName[" + i + "]"];
m.Description = coll["Description[" + i + "]"];
db.Manufacturers.Add(m);
db.SaveChanges();
}
}*
If it is so why not split contents based on comma, save each of them in two different string array. Then loop through each array's item saving name and description on each loop.
public ActionResult Student(StudentModel model, FormCollection frm)
{
string XmlData = "<Parent>";
var stuclass = frm.GetValues("stuclass");
var InstituteId = frm.GetValues("Institute");
var obtmark = frm.GetValues("obtmark");
var totalmark = frm.GetValues("totalmark");
var per = frm.GetValues("per");
int count = stuclass.Count();
for (int i = 0; i < count; i++)
{
XmlData += "<child><stuclass>" + stuclass[i] + "</stuclass>"
+ "<InstituteId>" + InstituteId[i] + "</InstituteId>"
+ "<obtmark>" + obtmark[i] + "</obtmark>"
+ "<totalmark>" + totalmark[i] + "</totalmark>"
+ "<per>" + per[i] + "</per>"
+ "</child>";
}
XmlData += "</Parent>";
model.XmlData = XmlData;
var res = studal.Insertdtl(model);
return View();
}

Differentiate between multiple dynamic fileupload controls

I'm dynamically adding multiple fileuploads to my asp.net page.
The user is able to create and delete these fileuploads from the page. The code for this is written in Javascript / JQuery:
var opleverpuntCounter = 0;
function addOpleverpunt() {
var $opleverpuntContainer = $('#opleverpuntContainer');
var div = '';
var divId = 'opleverpunt_' + opleverpuntCounter;
div = '<div id="' + divId + '"><br />Upload afbeelding situatie vooraf <input id="opleverpuntbeforefile_' + opleverpuntCounter + '" name="opleverpuntbeforefile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionbefore_' + opleverpuntCounter + '">Situatie omschrijving vooraf</label><br /><textarea type="text" id="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" name="opleverpuntdescriptionbefore_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br />Upload afbeelding situatie achteraf <input id="opleverpuntafterfile_' + opleverpuntCounter + '" name="opleverpuntafterfile_' + opleverpuntCounter + '" type="file" accept="image/*" capture="camera" /><br /><label for="opleverpuntdescriptionafter_' + opleverpuntCounter + '">Situatie omschrijving achteraf</label><br /><textarea type="text" id="opleverpuntdescriptionafter_' + opleverpuntCounter + '" name="opleverpuntdescriptionafter_' + opleverpuntCounter + '" rows="5" cols="100"></textarea><br /><input id="btn_' + opleverpuntCounter + '" type="button" value="REMOVE X" class="smallButton" /></div>';
$opleverpuntContainer.append(div);
$('#btn_' + opleverpuntCounter).click(function () { removeOpleverpunt(divId); });
opleverpuntCounter++;
}
function removeOpleverpunt(element) {
var $element = $('#' + element);
$element.remove();
}
It adds 2 fileupload controls on each addOpleverpunt() call. The name and id are both generated and unique for each fileupload.
HTML:
<div id="opleverpuntContainer">
</div>
Back at server-side I use following code to get and store the uploaded files:
for (int i = 0; i <= Request.Files.Count - 1; i++) {
HttpPostedFile PostedFile = Request.Files(i);
if (PostedFile.ContentLength > 0) {
//Store PostedFile here
//(Left out to improve question readability)
}
}
The fileuploads aren't ASP:FileUpload controls but regular input FileUpload controls.
Is there any way to differentiate between opleverpuntbeforefile_x and opleverpuntafterfile_x? (x is the generated number)
If I'm able to get the difference at serverside, I will be able to store opleverpuntbeforefile in one entity and opleverpuntafterfile in another.
Suggestions and answers in either C# or VB.NET are fine.
You can access the html control name:
for (int i = 0; i <= Request.Files.Count - 1; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
var controlName = Request.Files.Keys[i];
if (PostedFile.ContentLength > 0)
{
//Store PostedFile here
//(Left out to improve question readability)
}
}

Categories