how can set parameter values for params string[] parameter - arrays

I am required to produce the following address
http://example.com/Content/Details?cid=34&query=%D8%AA%D8%AD&positions%5B0%5D=true&positions%5B0%5D=false&positions%5B1%5D=false&positions%5B2%5D=false
this url after decode is :
http://example.com/Content/Details?cid=32&query=تحلیل&positions[0]=true&positions[0]=false&positions[1]=false&positions[2]=false
My action method contains the following parameters
public ActionResult Details(
string cid, string query, int? page, int id = 0, params string[] positions)
{
if(positions != null)
{
ViewBag.Title = positions[0];
ViewBag.Description = positions[1];
ViewBag.KeyWord = positions[2];
}
}
But when I set the parameters required for the positions parameter I get an error :
In fact i cant use positions[0] , positions[1] and positions[2] !!!
my cshtml page :
#{ title
#Html.CheckBox("positions[0]", ViewBag.Title as string)
description
#Html.CheckBox("positions[1]", ViewBag.Description as string)
keyword
#Html.CheckBox("positions[2]", ViewBag.KeyWord as string)
}
#Html.PagedListPager(Model, page => Url.Action("Details", new {cid = ViewBag.currentFilter, query= ViewBag.currentSearchString , positions[0]=ViewBag.title , positions[1]=ViewBag.Description ,position[2]=ViewBag.KeyWord,page }))
how can i set values for positions parameter in cshtml page ?
How can i set position[0] ,positions[2] and positions[3] ... i want know this just
the rest of my code is correct
please help me

You should read them in your controller and set them in ViewBag or ViewData:
ViewData["positons_0"] = Request.QueryString["positions[0]"];
ViewData["positons_1"] = Request.QueryString["positions[1]"];
// etc ...
Then you will be able to use them in your view also.
But I would suggest that you remove the square brackets from your querystring if possible. These are reserverd characters for IP v6 address literals (see here) and this is why you cannot use them in MVC. Your url should be:
http://example.com/Content/Details?cid=32&query=تحلیل&positions=true&positions=false&positions=false&positions=false
In this way you will be able to use it in both your controller:
public ActionResult Details(string cid, string query, int? page, int id = 0, string[] positions)
{
// ....
}
... and view:
#foreach(string position in Model.positions) // example
{
// ....
}

Related

How can I get an item by a string key using web api?

I can't figure out how to hit an endpoint like "api/GetItems/AB123" (AB123 of course being a string) and have it return that item from my data set. I read the docs on the FindAsync() method and it seemed to indicate that it would accept a string by default. Is there something I need to do to 'id' before passing it into FindAsync()? My DB does not have a primary key, if that matters. (I can't change that either, this is legacy data and I have no control over schema)
My db doesn't have a PK ID field. I need to do the next best thing and target a unique string field.
My GET method:
// GET: api/Items/5
[HttpGet("{id}")]
public async Task<ActionResult<Item>> GetItem(string id)
{
var item = await _context.Items.FindAsync(id); // Error happens here: "InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'."
if (item == null)
{
return NotFound();
}
return item;
}
Relevant from my model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string ItemId { get; set; }
Hello and welcome to the Stack Overflow Community!!
Instead of find you could do .SingleAsync() like the below.
You could also do a .Where(x => x.ItemId == id).SingleAsync(). But this is up to you.
// GET: api/Items/5
[HttpGet("{id}")]
public async Task<ActionResult<Item>> GetItem(string id)
{
var item = await _context.Items.SingleAsync(x => x.ItemId == id);
if (item == null)
{
return NotFound();
}
return item;
}
From your error it is obvious that int is expected in FindById method. Can you check the field type in database but from your model I would say that you don't have correct type.
String can't be used as Identity in this way because SQL Server doesn't know how to generate value for that.
You can check this post for more details on that: DatabaseGeneratedOption.Identity not generating an Id
So to conclude, you should check what do you really have in the database to determine is your model wrong.
If that is not the case and you do have a string in the db you should just retrieve item by using SingleAsync method (note that it will throw exception if the id is wrong).
var item = await _context.Items.SingleAsync(e => e.ItemId == id);
If you don't want an exception if the id doesn't exist you can use:
var item = await _context.Items.SingleOrDefaultAsync(e => e.ItemId == id);
which will return null for non existent id.

Azure Search - querying for ampersand character

I'm trying to find all records which contain & symbol, which is reserved. I'm using search, not $filter.
According to documentation, it can not be escaped with \%, and should be escaped as HTML url part to %26.
Trying SDK and Search explorer to find any options on how to search, but with no succeed:
&
*&*
*%26*
%26
\%26
UPD
Document example:
{
"test": "Hello & World"
Search query: search=%26&searchFields=test&$select=test
UPD 2
public class MyType
{
[System.ComponentModel.DataAnnotations.Key]
[IsFilterable]
public string Id { get; set; }
[IsSearchable, IsSortable]
public string Test { get; set; }
}
class Program
{
private static SearchServiceClient CreateSearchServiceClient()
{
string searchServiceName = "XXXXXX";
string adminApiKey = "XXXXXXX";
var serviceClient = new SearchServiceClient(searchServiceName, new SearchCredentials(adminApiKey));
return serviceClient;
}
static void Main(string[] args)
{
var client = CreateSearchServiceClient();
var def = new Microsoft.Azure.Search.Models.Index
{
Name = "temp-test-reserved1",
Fields = FieldBuilder.BuildForType<MyType>()
};
client.Indexes.Create(def);
var c = client.Indexes.GetClient("temp-test-reserved1");
var actions = new IndexAction<MyType>[]
{
IndexAction.Upload(new MyType{ Id = "1", Test = "Hello & World" }),
IndexAction.Upload(new MyType{ Id = "2", Test = "& test start" }),
IndexAction.Upload(new MyType{ Id = "3", Test = "test end &" })
};
c.Documents.Index(IndexBatch.New(actions));
}
}
search=%26&searchFields=Test&$select=Test
You likely can't find & because it's being removed at indexing and query time, since it's considered to be punctuation by the default analyzer. This article has more details on lexical analysis in Azure Cognitive Search. If you need to preserve ampersands while still tokenizing text on whitespace boundaries, you'll need to create a custom analyzer.
In the search explorer field on the Azure portal try the query &search=%26(as shown below)
In the SDK, only if you have set the UseHttpGetForQueries parameter to true, you would need to think of URL encoding the '&' character. By default, this parameter is set to false in which case you don't need to encode it.
More documentation about escaping/encoding here

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

How to get list/details url in Composite C1?

I build menu links so I need to know where I am.
The list url looks like: http://domain.com/list
The detail page url looks like: http://domain.com/list/detail
I could search for hardcoded /list part but it will be hardcoded.
I use the PathInfo function below and I always use 0 as parameter:
string PathInfo (int segment)
{
string pathInfo = C1PageRoute.GetPathInfo()??string.Empty;
string[] segments = pathInfo.Split('/');
string stringValue;
stringValue = segments.Skip(segment + 1).FirstOrDefault();
return stringValue;
}
...
// register the use of the path info
C1PageRoute.RegisterPathInfoUsage();
string kuruladi = PathInfo(0);
...
#foreach (var kurul in kurullar)
{
string currentpageitem = "";
if (kurul.KurulAdi == kuruladi)
{
currentpageitem = "current_page_item";
}
<li class="page_item page-item-1167 #currentpageitem">
#kurul.KurulAdi
</li>
}
Since I don't know where I am (list or detail) PathInfo(0) cannot help. An incorrect example link: http://domain.com/Sample-Detail-Page It should be http://domain.com/Kurul/Sample-Detail-Page
How can I write a much generic code to extract the exact location and then build the correct link? At least am I in list or detail, so I can use 0 or 1 as parameter.
#CurrentPageNode.Url was the missing part:
<li class="page_item page-item-1167 #currentpageitem">
#kurul.KurulAdi
</li>

read zip attachment in visualforce page

Hi all I am developing an app on salesforce.
I want to read the content of the file which is inside the zip attachment in visualforce page but without extracting the zip file.
How can I achieve this? Is there any way to do this?
Update for modified question:
Have a look at Handling Office Files and Zip Files in Apex – Part 2 by Andrew Fawcett.
There is a basic Knowledge Article on how to do this with an image that is stored in an Attachment. See How can I Display Base64 Data on page layout?
In this example the AttachmentID is passed via a query string paramemter, but you could look it up however works best for your requirement.
Visualforce page:
<apex:page controller="ViewImage" cache="true">
<img src="data:{!att.ContentType};base64,{!image}" />
</apex:page>
Controller:
public class ViewImage {
public Attachment att {
get {
if (att == null) {
String id = ApexPages.currentPage().getParameters().get('AttachmentID');
att = [SELECT Body, ContentType, Name FROM Attachment WHERE ID = :id];
}
return att;
}
private set;
}
public String image {
get {
return EncodingUtil.Base64Encode(att.body);
}
}
}
Hi all I have achieved this using JSzip library here is my code --
In apex page I have written javascript function --
function viewContent(){
var zip = null;
var zipFileName = null;
var zipFileNames = null;
data = "{!contentAsText}";
zip = new JSZip(data, {base64:true});
zipFileName = 'files.zip';
zipFileNames = [];
for(var zipfileName in zip.files){
zipFileNames.push(zipfileName);
if(zipfileName == 'index.html'){
var file = zip.files[zipfileName];
var data = file.data;
document.getElementById('contentdiv').innerHTML = data;
//var data = JSZipBase64.encode(file.data);
}
}
In controller --
public String contentAsText {get;set;}
List<Attachment> atts = [Select Id, Body from Attachment where name='files.zip' limit 1];
contentAsText = EncodingUtil.base64Encode(atts[0].Body);
This link will help you --
http://andyinthecloud.com/2012/12/09/handling-office-files-and-zip-files-in-apex-part-2/

Resources