Differentiate between multiple dynamic fileupload controls - c#

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)
}
}

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

Can I make jQuery read tag helpers of ASP.NET Core 2.1 ? Seems it's completely ignoring them

Can jQuery read the asp-for tag helpers and asp-action? It seems from what I've seen that just ignores them how can I get around this problem or solve it? (I can't change jQuery approach).
What can I do guys? Is there a way to do what I'm trying to do: displaying those elements and at the same time saving some values in database (be aware I have to append multiple elements)?
$('#results').append('<form method="post"><div class="item col-xs-4 col-lg-4">'
+ '<div class="thumbnail">'
+ '<iframe width="100%" height="200px" allowfullscreen src="https://www.youtube.com/embed/' + id + '"></iframe>'
+ '<div class="caption">'
+ '<p class=" group inner list-group-item-text" style="overflow:hidden;text-overflow:elipsis;white-space:nowrap;">' + vidTitle + '</p>'
+ '<div class="row">'
+ '<input type="text" value="' + id + '" asp-for="Input.vLink" hidden />'
+ '<input type="text" value="' + vidTitle + '" asp-for="Input.vLink" hidden />'
+ '<div class="col-xs-12 col-md-6">'
+ '<button asp-action="AddToPlaylist" type="submit" asp-route-vLink="' + id + '"asp-route-vTit="' + vidTitle + '" id="' + vidTitle + '" data-key="' + id + '" class="btn btn-success" onclick="AddToPlaylist()">Add to Playlist</button>'
+ '</div></div></div></div></div></form>');
})
$('#playlist').append('<form method="post"><div">'
+ '<input type="text" value="' + id + '" asp-for="Input.vLink" hidden />'
+ '<input type="text" value="' + vidTitle + '" asp-for="Input.vLink" hidden />'
+ '<div class="list-inline"><li style="width:89%;overflow:hidden;text-overflow:elipsis;white-space:nowrap;list-style-type:none;">' +
VideoTitulli + ' ' + id
+'</li>'+' '+'<button value="' + id + '" style="border-radius:10px" class="fas fa-times" asp-action="RemoveFromPlaylist" asp-route-vLink="' + id + '"asp-route-vTit="' + vidTitle + '" onclick="RemoveFromPlaylist()"></button></div><hr class="hrC" /></div</form>')
.net core actions
public async Task AddToPlaylist(string userId)
{
var userplaylist = new UserPlaylist() { ResultTitles = Input.vTit,ResultLinks = Input.vLink, ApplicationUserId = userId};
_context.UPlaylist.AddAsync(userplaylist);
await _context.SaveChangesAsync();
}
public async Task RemoveFromPlaylist(string userId)
{
var userplaylit = new UserPlaylist() { ResultTitles = Input.vTit, ResultLinks = Input.vLink, ApplicationUserId = userId };
_context.UPlaylist.Remove(userplaylit);
await _context.SaveChangesAsync();
}
This won't work, Tag Helpers run server side to generate HTML for the client. JQuery can not see these Tag Helpers.
If you run HTML with Tag Helpers and look at the generated code, you'll see there's no asp- attributes, only HTML which the Tag Helpers have generated for you.
Therefore if you want to add HTML to the page, you'll need to do it manually instead.
For more information on Tag Helpers:
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1

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.

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);
});
});
});
});

Categories