Add #Html.DropDownList using Jquery - c#

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

Related

Insert array html in C# ASP.NET

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

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.

I want to change the list of images based on user selection in JSON and MVC

I'm trying to generate a list on user selection with the help of json in MVC. On page load the list will contain all the images but when the user clicks a link specifying a particular image group. Then images in that group should be shown only.
The problem is however all the images are loaded successfully on page. When I click the linkbutton for particular group it gives me a Json string with that group and redirects to Json actionresult.
Please help I'm very new to using Json.
Razor View:-
#foreach (var item in Model.ImageObj)
{
using (Html.BeginForm("getImageClick", "Home", new { grp = item.ImgGroup }))
{
<button class="btn btn-sm" type="submit" value="#item.ImgGroup" onclick="getImageClick()">#item.ImgGroup </button>
}
}
<div class="clearfix"></div>
<div class="table-bordered" style="margin-top:40px"></div>
<div class="container" style="margin-top:10px">
<div id="status" style="font-size:20px"></div>
<table id="tbl" class="table table-responsive table-hover table-bordered text-center" style="font-size:20px"></table>
<script language="javascript">
$("#status").text("Loading...");
$.get("getImage", null, BindData);
function BindData(Images) {
var tbl = $("#tbl");
for (var j = 0; j <= Images.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + Images[j].Image + " " + 'alt="' + Images[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + Images[j].Description + "</td>" +
"</tr>"
// +
// "<tr class='col-md-4'>" +
//"<td class='col-md-12'>" + Images[j].Description + "</td>" +
//"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
$.get("getImageClick", null, BindDataNew);
function BindDataNew(ImagesNew) {
var tbl = $("#tbl");
for (var j = 0; j <= ImagesNew.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + ImagesNew[j].Image + " " + 'alt="' + ImagesNew[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + ImagesNew[j].Description + "</td>" +
"</tr>"
// +
// "<tr class='col-md-4'>" +
//"<td class='col-md-12'>" + Images[j].Description + "</td>" +
//"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
</script>
Controller Methods:-
public ActionResult getImage() //JSON Collection
{
Thread.Sleep(4000);
List<ImageTbl> Images = DbContext.ImageTbls.ToList<ImageTbl>();
return Json(Images, JsonRequestBehavior.AllowGet);
}
public ActionResult getImageClick(string grp) //JSON Collection
{
Thread.Sleep(4000);
List<ImageTbl> ImagesNew = DbContext.ImageTbls.Where(x => x.ImgGroup == grp).ToList<ImageTbl>();
return Json(ImagesNew, JsonRequestBehavior.AllowGet);
}
Even though your button has an onclick event handler, It is inside a form and clicking on that will do a normal form submit. The form's action attribute value is set to getImageClick and it returns JSON data. That is the reason you are seeing json data when you click on the button.
What you should do is, prevent the normal form submit behavior so that it will execute the js code which makes the ajax call and get the data and update the DOM.
Here is the unobtrusive ajax way of doing it.
#foreach (var item in Model.ImageObj)
{
<button class="btn grpBtn"
data-url="#Url.Action("getImageClick", "Home", new { grp = item.ImgGroup})">
#item.ImgGroup
</button>
}
This will add a css class grpBtn to the button.It also add a data attribute called url with value as the relative url to the getImageClick action method with the group in the query string with key grp Now listen to the click event on this button, read the data-url value and make the ajax call to that.
$(function(){
$(document).on("click",".grpBtn",function(e){
e.preventDefault(); //prevents normal link click behavior
$("#tbl").empty(); //clear existing images
$.getJSON($(this).data("url"),function(data){
//loop through the items in data and build the markup for table
$.each(data,function(a,item)
{
var newRow="<tr><td>"+item.Image="</td><tr>"; //Fix this as needed for your use case
$("#tbl").append(newRow);
});
});
});
});

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