Creating jquery object array and posting its values on form submit - c#

I have dynamicly added html elements(selectlists) in a form :
//Dynamicly adding selectlist elements
function newshit() {
i = i + 1
$("#mytable").append("<tr><td><div id='div" + i + "'><select id='elem" + i + "' name='elem" + i + "' class='ted'></select><input type='button' value='-' id='buttonminus" + i + "' style='width:5%;' onclick='removeelem(elem" + i + ",buttonminus" + i + "," + i + ")'/></div></td></tr>")
getitems("elem" + i)
}
//filling lists
function getitems(item) {
$.getJSON('#Url.Content("~/Stok/Items/")', {}, function (data) {
$.each(data, function (i, c) {
$("#" + item).append("<option value='" + c.Value + "' title='" + c.Text + "' label='" + c.Text + "'>" + c.Text + "</option>")
})
})
}
//removing element, when button next to it used
function removeelem(elem,buttonminus,i) {
if ($("select").length > 1) {
$("#div" + i).closest('tr').empty().remove()
} else if ($("select").length <= 1) {
alert("At least 1 of items must be chosen to create a group!")
}
}
//checking elements and values existence
function check() {
var slcts = $("select").serialize();
alert(slcts)
}
im trying to get the value of each selectlist's selected option value and put them into an array than send them to my controller on form submit.
How can i achive this?

Need to check this, but I think that the following should work:
Change your code so that the format of your ids is something like:
id="elem[0]"
Then if your controller has a signature something like this:
public ActionResult Something(IEnumerable<string> elem)
{
}
Then his should "just work".

You could use something like -
var selectdata = $("select").serialize()
This will return a string in the form <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2> etc. You'd need to add a 'name' attribute to your select HTML when you create it for this to work.
Demo - http://jsfiddle.net/ipr101/fZXha/
You could then put the selectdata variable in a hidden field before the form was posted or send it via AJAX using the ajax or post methods.

Related

Updating front end during postback

I have a method that runs through a loop that can take quite a while to complete as it requires getting data back form an API.
What I would like to do is display a message on the front end explaining how the system is progressing during each loop. Is there a way to update the front end while processing?
public static void GetScreenshot(List<string> urlList, List<DesiredCapabilities> capabilities, String platform, Literal updateNote)
{
foreach (String url in urlList)
{
String siteName = new Uri(url).Host;
String dir = AppDomain.CurrentDomain.BaseDirectory+ "/Screenshots/" + siteName + "/" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
foreach (DesiredCapabilities cap in capabilities)
{
String saveDirectory = "";
if (platform == "btnGenDesktopScreens")
{
saveDirectory = dir + "/" + cap.GetCapability("os") + "-" + cap.GetCapability("os_version") + "-" + cap.GetCapability("browser") + cap.GetCapability("browser_version");
}
else if(platform == "btnMobile")
{
saveDirectory = dir + "/" + cap.GetCapability("platform") + "" + cap.GetCapability("device") + "-" + cap.GetCapability("browserName");
}
updateNote.Text += "<br/>" + cap.GetCapability("platform") + " - " + cap.GetCapability("device") + "-" + cap.GetCapability("browserName");
//I'd like to display a message here
TakeScreenshot(url, cap, saveDirectory);
//I'd like to display a message here
}
}
}
Has anyone come across a method of doing this?
Depending on how you're returning the feedback to the user, you might be able to do this by using HttpResponse.Flush in a loop to push parts of the HTML response to the user a bit at a time. See https://msdn.microsoft.com/en-us/library/system.web.httpresponse.flush(v=vs.100).aspx

Check if a GET method is Null/Empty

I have recently been working with a <select> tag, however, I have noticed you cannot determine, using an if statement if the GET is NULL or equal to "".
var tbl_st = (from c in db.tblfsk_style select c).ToArray();
build.Append("<select id='style' name='style' class='styles'>");
foreach (var style in tbl_st)
{
build.Append("<option value='" + style.StyleID + "'>" + style.Description + "</option>");
}
build.Append("</select>");
if(Request.QueryString["style"] != "")
{
var choosen = Request.QueryString["style"];
var tbl_colour = (from c in db.tblfsk_style_colour where c.StyleID == choosen select c).ToArray();
build.Append("<select id='colour' name='colour' class='styles'>");
foreach (var colour in tbl_colour)
{
build.Append("<option value='" + colour.ColourID + "'>" + colour.ColourID + "</option>");
}
build.Append("</select>");
}
build.Append("<button type='submit' class='btn'>Continue</button>");
The idea is when they choose Continue as a Button the next thing loads up but I am struggling to find a way to check if the style is null or not.
I have tried:
if(Request.QueryString["style"] != "") { // next <select> tag
And:
if(!string.IsNullOrEmpty(Request.QueryString["style"])) { // next <select> tag
Is there a way to determine if the style is null in the GET?
PHP example of doing this (to explain better):
if(isset($_GET['style'])) { // next <select> tag
I fixed this by trying using the try and catch method.
try
{
var sty_in = Request.QueryString["style"].ToString();
build.Append("test");
}
catch(Exception)
{
var tbl_st = (from c in db.tblfsk_style select c).ToArray();
build.Append("<select id='style' name='style' class='styles'>");
foreach (var style in tbl_st)
{
build.Append("<option value='" + style.StyleID + "'>" + style.Description + "</option>");
}
build.Append("</select>");
}
So if it has been inputted, we can replace test with putting our new <select> statement.
Or even easier:
if(!string.IsNullOrEmpty(Request.QueryString["style"].ToString())){ }
Or
if(Request.QueryString["style"].ToString() != null) { }
I was missing the ToString()
You are using Request.QueryString so the value should be passed through the URL as a GET parameter. You can easily see the value of style if it is passed correctly through the URL string.

jquery ASP.Net "Invalid expression term '{'"

I am using jQuery in ASP.Net mvc 5 website project.
This is my code
function loadTableWorkshops() {
#foreach (var item in Model) {
var row = jQuery("<tr></tr>").append("<td>" + item.title + "</td><td>" + item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(item.wid, item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + item.wid + "&wstitle=" + item.title)
.addClass("details");
...
} //foreach
} //function
the error that I receive is
CS1525: Invalid expression term '{'
and it references this line of code
var deletebtn = jQuery("<a>Delete</a>").attr({
I tried to initialize the var deletebtn in one line but the problem is still there. I am sure that jQuery is included properly in my project since it works fine in other places of the project and in the same file too.
When you use #foreach .. { the following statements are c# statements until the closing } - but you've put javascript/jquery statements there instead.
Without checking, you should be able to do:
function loadTableWorkshops() {
#foreach (var item in Model) {
// item is server-side so needs #item
<text>
var row = jQuery("<tr></tr>").append("<td>" + #item.title + "</td><td>" + #item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(#item.wid, #item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + #item.wid + "&wstitle=" + #item.title)
.addClass("details");
...
</text>
} //foreach
}
but you might want to completely rethink how you are generating your dynamic html.
For example, you could convert your model to javascript first, then use pure js to manipulate it, eg:
function loadTableWorkshops() {
var items = '#Model.ToString()'; // convert here, maybe use JSON if you haven't overridden ToString()
items.each(function() {
var item = this;
var row = jQuery("<tr></tr>").append("<td>" + item.title + "</td><td>" + item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(item.wid, item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + item.wid + "&wstitle=" + item.title)
.addClass("details");
...
} //each
}
The key will be in how you convert Model to items - it's unlikely ToString will suffice, but should get you closer.

Why 'innerhtml' does not work properly for 'select' tag

I am trying to set the innerhtml of an html select tag but I cannot set this feature;therefor,I need to use the outerhtml feature.This way,not only is my code HARDCODE ,but also it is preposterous.I have already read 'InnerHTML IE 8 doesn't work properly? Resetting form',it did not help though.
I would really appreciate it if you tell me how to set the innerhtml feature of an html select tag.
My C# code:
public void SetDefaultValue(string ControlID, string ControlValue)
{
System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
HtmlElement HTMLControl = doc.GetElementById(ControlID);
string ListResult;
string ListInnerHTML = "";
ListInnerHTML += "<OPTION value = " + LstString + ">" + LstString + "</OPTION>";
ListResult = "<SELECT id = " + '"' + HTMLControl.Id + '"' + " type = " + '"' + HTMLControl.GetAttribute("type") + '"' + " title = " + '"' +
HTMLControl.GetAttribute("title") + '"' + " name = " + '"' + HTMLControl.Name + '"' + " value = " + '"' + HTMLControl.GetAttribute("value") +
'"' + " size = \"" + HTMLControl.GetAttribute("size") + '"' + HTMLControl.GetAttribute("multiple").ToString() + "\">" + ListInnerHTML + "</SELECT>";
HTMLControl.OuterHtml = ListResult;
}
or
string _lsthtml = _htmlel.OuterHtml;
string[] _parts = ControlValue.Split(new char[] { ',' });
string _lstinner = "";
foreach (string _lst in _parts)
_lstinner += "<option value=" + _lst + ">" + _lst + "</option>";
_lsthtml = _lsthtml.Insert(_lsthtml.IndexOf(">") + 1, _lstinner);
_htmlel.OuterHtml = _lsthtml;
This code works but I need something efficient and clean.
The ReturnControlType function returns the type of an html tag.
This is an official Internet Explorer bug:
BUG: Internet Explorer Fails to Set the innerHTML Property of the Select Object.
One workaround
You may try adding one of the following meta tags in your document's head:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
or
<meta http-equiv="X-UA-Compatible" content="IE=10" />
You should also properly format the option tag's value attribute (enclose LstString in '):
ListInnerHTML += "<OPTION value='" + LstString + "'>" + LstString + "</OPTION>";
A more reliable solution
As the fixes above might be a workaround for your code, I would suggest to use a more reliable approach. Consider adding a reference to Microsoft.mshtml to your project and modifying your method like this:
// add this to the top of the file containing your class
using mshtml;
public void SetDefaultValue(string ControlID, string ControlValue)
{
System.Windows.Forms.HtmlDocument doc = webBrowser1.Document;
IHTMLDocument2 document = doc.DomDocument as IHTMLDocument2;
var sel = doc.GetElementById(ControlID);
HTMLSelectElement domSelect = (HTMLSelectElement)sel.DomElement;
domSelect.options.length = 0;
HTMLOptionElement option;
// here you can dynamically add the options to the select element
for (int i = 0; i < 10; i++)
{
option = (HTMLOptionElement)document.createElement("option");
option.text = String.Format("text{0}", i);
option.value = String.Format("value{0}", i);
domSelect.options.add(option, 0);
}
}
I really don't know why innerHTML is not working for you.
If it just dosen't you could try an alternative:
http://innerdom.sourceforge.net/
demo
In this thread it is sugested you use the items collection of a control
How to add items to dynamically created select (html) Control
refer to this page for a complete example:
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlselect.items.aspx

How to retrieve an annotation in web resource and display it using popup window - crm 2011

How to show annotation present in an entity in popup window by using html web resource. My requirement is to display annotation present in an entity in a popup window and in popup window user should be able to delete , upload and convert the annotation to pdf (if he wants). Can you suggest a best method to achieve this in crm 2011.
function retann() {
//debugger;
var serverUrl = Xrm.Page.context.getServerUrl();
var GUIDvalue = Xrm.Page.data.entity.getId();
// Creating the Odata Endpoint
var oDataPath = "http://url/organization/XRMServices/2011/OrganizationData.svc/";
var retrieveReq = new XMLHttpRequest();
var Odata = oDataPath + "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + GUIDvalue + "'";
retrieveReq.open("GET", Odata, false);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveReq.onreadystatechange = function () { retrieveReqCallBack(this); };
retrieveReq.send();
}
function retrieveReqCallBack(retrieveReq) {
if (retrieveReq.readyState == 4 /* complete */) {
//debugger;
var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
var message = "";
var fun_var =
"<script type=text/javascript>" +
"function result_value()" +
"{" +
"var rad_val;" +
"for (var i=0; i < document.orderform.test.length; ++i){if (document.orderform.test[i].checked){rad_val = document.orderform.test[i].value;}}" +
"if(rad_val==null || rad_val=='')" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue('0');" +
"}" +
"else" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue(rad_val);" +
"}" +
" window.top.opener.Xrm.Page.data.entity.attributes.get('new_fireplugin').setValue(1);" +
"window.top.opener.Xrm.Page.data.entity.save();" +
"this.window.close();" +
"}" +
"function result_value1()" +
"{" +
"var rad_val1;" +
"for (var i=0; i < document.orderform.test.length; ++i){if (document.orderform.test[i].checked){rad_val1 = document.orderform.test[i].value;}}" +
"if(rad_val1==null || rad_val1=='')" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue('0');" +
"}" +
"else" +
"{" +
"window.top.opener.Xrm.Page.data.entity.attributes.get('new_radiovalue').setValue(rad_val1);" +
"}" +
" window.top.opener.Xrm.Page.data.entity.attributes.get('new_delete').setValue(1);" +
"window.top.opener.Xrm.Page.data.entity.save();" +
"this.window.close();" +
"}" +
"</script>";
var n = retrieved.results.length;
for (var i = 0; i < retrieved.results.length; i++) {
message += " <input type='radio' name='test' value=' " + i + "' />" + retrieved.results[i].FileName + "<br />";
}
myWindow = window.open('', '', 'width=500,height=150,left=250,top=250,scrollbars=yes,resizable=yes,directories=yes');
myWindow.document.write(fun_var + "<body bgcolor=GhostWhite style='font-family:verdana;font-size:11px;'><form name='orderform' style='font-family:verdana;font-size:11px;'>" + message + "</br><center ><input type='button' onclick='result_value()' style='font-family:verdana;font-size:11px;' value='Convert To PDF'/></center>" + "</form>");
myWindow.focus();
}
}
function SetField() {
var AddressType = Xrm.Page.data.entity.attributes.get("new_radiovalue");
AddressType.setValue("");
}
function save_form() {
// var MainPhone = Xrm.Page.data.entity.attributes.get("new_name").getValue();
//Xrm.Page.data.entity.attributes.get("new_name").setValue(MainPhone+".");
Xrm.Page.data.entity.save();
}
retrieveReqCallBack(this) function displays the popup with annoatation. Using the above code i'm able to convert doc to pdf. Since i want to add multiple functionalities like upload , delete and convert to pdf. If annotation is present then popup should have option to upload and if annotation is present then it has to show delete and convert to pdf buttons.
I found this as solution to my question,
You'll need to create a custom web resource (html) with javascript to pull the data out of the sub-grid, parse the rows, query the crm data via REST or SOAP to see if there is an annotation, then put an icon of the 'paperclip' which'll allow users to upload attachments against that record.

Categories