jquery ASP.Net "Invalid expression term '{'" - c#

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.

Related

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.

C# removing duplicate HTML rows

I'm generating a HTML file using C#. Using objects and their properties, I'm adding rows to an HTML table . However, I'm seeing some duplicate rows which I don't want, even though the column values are correct. After doing some googling, I found a few HTML functions that people posted for accomplishing this, such as:
function removeDuplicateRows($table){
function getVisibleRowText($row){
return $row.find('td:visible').text().toLowerCase();
}
$table.find('tr').each(function(index, row){
var $row = $(row);
$row.nextAll('tr').each(function(index, next){
var $next = $(next);
if(getVisibleRowText($next) == getVisibleRowText($row))
$next.remove();
})
});
}
and
var seen = {};
$('table tr').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
However, I'm not sure how to utilize those in my c# code (possibly from my lack of HTML coding). When I tried using these and wrap each line with a sw.WriteLine, all I get is text of the function. So my question is, how can I remove duplicate HTML table rows in my code?
What I have:
StreamWriter sw = new StreamWriter(Path.Combine(cdsPublishRoot, "GeneralActive.htm"));
sw.WriteLine("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \" http://www.w3.org/TR/html4/strict.dtd \">");
sw.WriteLine("<html>");
sw.WriteLine("<head>");
sw.WriteLine("<meta http-equiv=\"Expires\" content=\"0\">");
sw.WriteLine("<title>GPCSE-CDS General</title>");
sw.WriteLine("</head>");
sw.WriteLine("<body onmousemove=\"MouseMove(event)\">");
sw.WriteLine("<script type=\"text/javascript\">");
sw.WriteLine("DoMainMenu(false,\"SDS\");");
sw.WriteLine("DoSdsSubMenu(true,\"ARCHIVE\");");
sw.WriteLine("</script>");
sw.WriteLine("<p class=Heading2><br>Active PCM General Requirement Specifications<br></p>");
sw.WriteLine("<table cellpadding=5 cellspacing=0 border=1 width=760 id=\"MainDataTable\">");
sw.WriteLine("<tr><th style=\"width:14%\" align=left class=SdsHeader>Spec.</th>");
sw.WriteLine("<th style=\"width:64%\" align=left class=SdsHeader>Specification Name</th>");
sw.WriteLine("<th style=\"width:7%\" align=left class=SdsHeader>Spec. Ver.</th>");
sw.WriteLine("<th style=\"width:7%\" align=left class=SdsHeader>Rev. Level</th>");
sw.WriteLine("<th style=\"width:8%\" align=left class=SdsHeader>Rev. Date</th></tr>");
foreach (string file in genActive.Distinct())
{
string[] genOldDirectories = file.Split(Path.DirectorySeparatorChar);
string path = Path.GetDirectoryName(file);
string[] files = Directory.GetFiles(path);
var acro = ArdApp.Data.GeneralSpecification.GeneralSpecVersion.DataLoad(genOldDirectories[2].ToString(), Convert.ToInt32(genOldDirectories[3][0].ToString()), Convert.ToInt32(genOldDirectories[3][2].ToString() + genOldDirectories[3][3].ToString()));
sw.WriteLine("<tr><td id=\"idTDMenuTitle0008\">");
sw.WriteLine("<div id=\"idMenuTitle0008\" class=\"clsMenuTitle\" onclick=\"DoMenu(this)\">");
sw.WriteLine(genOldDirectories[2] + "</div>");
sw.WriteLine("<div id=\"idMenu0008\" class=\"clsMenu\">");
sw.WriteLine("<ul class=\"clsMenuBullets\">");
foreach (var fileName in files)
{
string[] fileDirectory = fileName.Split(Path.DirectorySeparatorChar);
sw.WriteLine("<li class=\"clsMenuItem\"><a class=\"clsMenuItem\" href=" + StripToWebFriendlyName(file) + ">" + StripToWebFriendlyName(fileDirectory[5]) + "</a></li>");
}
sw.WriteLine("</ul>");
sw.WriteLine("</div></td>");
sw.WriteLine("<td class=BodyText>" + acro.AcronymName + "</td>");
sw.WriteLine("<td class=BodyText>" + Convert.ToInt32(genOldDirectories[3][0].ToString()) + "</td>");
sw.WriteLine("<td class=BodyText>" + genOldDirectories[3][2].ToString() + genOldDirectories[3][3] + "</td>");
sw.WriteLine("<td class=BodyText>" + acro.RevisionDate + "</td>");
sw.WriteLine("</tr>");
}
sw.WriteLine("</table>");
sw.WriteLine("</Body>");
sw.WriteLine("</HTML>");
sw.Close();
}
What I tried:
....
foreach (var fileName in files)
{
string[] fileDirectory = fileName.Split(Path.DirectorySeparatorChar);
sw.WriteLine("<li class=\"clsMenuItem\"><a class=\"clsMenuItem\" href=" + StripToWebFriendlyName(file) + ">" + StripToWebFriendlyName(fileDirectory[5]) + "</a></li>");
}
sw.WriteLine("</ul>");
sw.WriteLine("</div></td>");
sw.WriteLine("<td class=BodyText>" + acro.AcronymName + "</td>");
sw.WriteLine("<td class=BodyText>" + Convert.ToInt32(genOldDirectories[3][0].ToString()) + "</td>");
sw.WriteLine("<td class=BodyText>" + genOldDirectories[3][2].ToString() + genOldDirectories[3][3] + "</td>");
sw.WriteLine("<td class=BodyText>" + acro.RevisionDate + "</td>");
sw.WriteLine("</tr>");
}
sw.WriteLine("var seen = {};");
sw.WriteLine("$('table tr').each(function() {");
sw.WriteLine("var txt = $(this).text();");
sw.WriteLine("if (seen[txt])");
sw.WriteLine(" $(this).remove();");
sw.WriteLine("else");
sw.WriteLine("seen[txt] = true;");
sw.WriteLine("});");
Looks like your just reading in file info and just want to display distinct files in your HTML display?
If this is still a c# question, consider just reading in the file info (full file path info) into a List<string> and then you could use linq "Distinct" to get your non-duplicated items and then output in html as needed.

Map 2 properties for same data base column in Entity Framework

I am working on EF 4.1 code first development with MVC and c#.
This is my Requirement:
Is there any way to map 2 properties of my model class for same database column ?
B'cos I am having data retrieval issue like below.
Currently mapped property for db column having some complex calculation.
So that When I call it from my UI as a ajax call it retrieves calculated value as 0.0, b'cos of that calculation delay (when i put a debug and then slow the things it will correctly generate value).
If I set another field which does not having any calculation it shows correctly.
How to overcome above issue ?
Part of my model code as below.
public class Invoice
{
public Invoice() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public Guid Id { get; set; }
public decimal LatestTotal { get; set; }
[NotMapped]
public decimal Total
{
get
{
return (LatestTotal = this.CalculateTotal());
}
}
}
Problematic property is LatestTotal
Action Method Looks like below
public ActionResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey, DateTime checkoutDate, double checkoutTime)
{
var items = new List<CheckOutServiceAndRetailItem>();
TimeSpan timeResult = TimeSpan.FromHours(checkoutTime);
var checkOut = checkoutDate + timeResult;
var serviceDetails = Repository.GetAllPayableItems(checkOut, invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
//Price = s.Total,
Class = s.Allocation.Service.IsAnExtra ? "RetailOrExtraService" : "",
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Ajax call from UI looks like below.
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey, checkoutDate: checkoutDate, checkoutTime: checkoutTime },
success: function (response) {
make = "<table id='tblPayment'>";
var totalToBepaid = 0.0;
toBePaidItems = [];
$.each(response, function (index, sr) {
if (unPaid) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
} else {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td></tr>";
}
totalToBepaid += sr.Price;
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
var lateFee = parseFloat($("#hdnLateFee").val());
if (lateFee > 0) {
totalToBepaid += lateFee;
make += "<tr class='Fees'><td style='padding-right:100px'>Late Pickup Fee</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + lateFee + "</td></tr>";
}
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
UI Image as below (when I put a brake point and run then correct value shows)

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.

Creating jquery object array and posting its values on form submit

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.

Categories