Building a URL with ActionLinks from within a Controller in MVC - asp.net-mvc

I'm building a basic flashcard application - a Set contains Cards and other Sets. When navigating to something like Set1 > Set2 > Set3, I want each of the parent "Sets" to link to their respective details page. I'm passing the Details viewModel a string called "breadcrumbs", which contains something like this:
var stringBuilder = "";
var parent = model.ParentSet;
while (parent != null)
{
stringBuilder += "<li><a href=\"#Url.Action('Detail', 'Set', new {SetId = \" + parentSetId + \"}, null)'>" + parent.Name + "</a> <span class='divider'>/</span></li>";
parent = parent.ParentSet;
}
model.Breadcrumbs =
"<li>Home <span class='divider'>/</span></li>" +
stringBuilder + "<li class='active'>New Set</li>";
model.Name = "New Set";
The URLs being generated are literal though - containing "#Url.Action".
Does anyone know how I can get this to work, or if there's a better way to do it?

Just evaluate it:
"<li><a href='" + Url.Action('Index', 'Home') + "'>..."

I think an important question here is, "What does your view look like?"
If your view is using that model.Breadcrumbs field like this:
...
<div id="breadcrumbs">
#model.Breadcrumbs
</div>
...
The #Url.Action call in the string you've built will never be executed. The Razor engine operates on the code it finds in the view file, not on fields within the model.
You need to do one of two things:
Rather put "#Url.Action(...)" into the string you're constructing, figure out what the Url is on the server side using something like Url.Link() and insert that directly.
(and this is better) Pass those parents to the view as part of the view model and loop over them in the view, constructing the tags as you go. Normally you don't want to put html into a model. The model's there to hold data, not presentation code.

Related

How does partial views work?

In a MVC master view I have this:
#Html.Partial("_CreateOrEdit", Model)
and the partial view _CreateOrEdit contains this code block:
#{
var item = Model;
.
.
.
string favouriteId = "fav_" + item.Id + "_comment";
}
Despite ensuring that item.Id > 0 I get a null reference error in pointing at the declaration of favouriteId. The dots mean there are many other similar declarations all with non null reference.
When I replace item.Id by #item.Id, rendering the partial views fail in the master view.
What am I doing wrong? Can someone point to a complete tutorial on code blocks please?
Thanks
Another '#' cannot be used since the statement is already within the razor code block.
In order to avoid the object reference exception, use the below code
string favouriteId = string.Format("{0}_{1}_{2}", "fav", item.Id, "comment");

Append to query-string with the same key

I am trying to add some parts to a query-string with the same key.
I have a url like http://server.com/search/result?query=hello with some controls that should add a collaborator to the query-string.
This is done with this:
<g:link action="result" params="${params + ['collaborator': collaborator.id]}">${collaborator.name}</g:link>
Which returns: http://server.com/search/?query=hello&collaborator=<id>.
This is all good, but its possible to choose more collaborators. How do I append another &collaborator=<id> to the query?
I have tried various methods like ${params + [params.collaborator + collaborator.id]}, but this only puts them in one string.
Try this:
gsp:
<g:link action="result" params="${params + ['collaborator': params.list('collaborator') + [collaborator.id]]}">${collaborator.name}</g:link>
action:
List collaboratorList = params.list('collaborator')
//Your operations on this list

Looking for guide line about Razor syntax in asp.net mvc

i am learning asp.net mvc just going through online tutorial
1) just see <span>#model.Message</span> and #Html.Raw(model.Message)
suppose if "Hello Word" is stored in Message then "Hello Word" should display if i write statement like
<span>#model.Message</span> but i just could not understand what is the special purpose about #Html.Raw(model.Message).
what #Html.Raw() will render ?
please discuss with few more example to understand the difference well.
2) just see the below two snippet
#if (foo) {
<text>Plain Text</text>
}
#if (foo) {
#:Plain Text is #bar
}
in which version of html the tag called was introduce. is it equivalent to or what ? what is the purpose of
this tag ?
just tell me about this #:Plain Text is #bar
what is the special meaning of #: ?
if our intention is to mixing text with expression then can't we write like Plain Text is #bar
3) <span>ISBN#(isbnNumber)</span>
what it will print ? if 2000 is stored in isbnNumber variable then it may print <span>ISBN2000</span>. am i right ?
so tell me what is the special meaning of #(variable-name) why bracket along with # symbol ?
4) just see
<span>In Razor, you use the
##foo to display the value
of foo</span>
if foo has value called god then what this ##foo will print ?
5 ) see this and guide me about few more syntax given below point wise
a) #(MyClass.MyMethod<AType>())
b)
#{
Func<dynamic, object> b =
#<strong>#item</strong>;
}
#b("Bold this")
c) <div class="#className foo bar"></div>
6) see this
#functions
{
string SayWithFunction(string message)
{
return message;
}
}
#helper SayWithHelper(string message)
{
Text: #message
}
#SayWithFunction("Hello, world!")
#SayWithHelper("Hello, world!")
what they are trying to declare ? function ?
what kind of syntax it is ?
it seems that two function has been declare in two different way ? please explain this points with more sample. thanks
Few More question
7)
#{
Func<dynamic, object> b = #<strong>#item</strong>;
}
<span>This sentence is #b("In Bold").</span>
what the meaning of above line ? is it anonymous delegate?
when some one will call #b("In Bold") then what will happen ?
8)
#{
var items = new[] { "one", "two", "three" };
}
<ul>
#items.List(#<li>#item</li>)
</ul>
tell me something about List() function and from where the item variable come ?
9)
#{
var comics = new[] {
new ComicBook {Title = "Groo", Publisher = "Dark Horse Comics"},
new ComicBook {Title = "Spiderman", Publisher = "Marvel"}
};
}
<table>
#comics.List(
#<tr>
<td>#item.Title</td>
<td>#item.Publisher</td>
</tr>)
</table>
please explain briefly the above code. thanks
1) Any kind of #Variable output makes MVC automatically encode the value. That is to say if foo = "Joe & Dave", then #foo becomes Joe & Dave automatically. To escape this behavior you have #Html.Raw.
2) <text></text> is there to help you when the parser is having trouble. You have to keep in mind Razor goes in and out of HTML/Code using the semantics of the languages. that is to say, it knows it's in HTML using the XML parser, and when it's in C#/VB by its syntax (like braces or Then..End respectively). When you want to stray from this format, you can use <text>. e.g.
<ul>
<li>
#foreach (var item in items) {
#item.Description
<text></li><li></text>
}
</li>
</ul>
Here you're messing with the parser because it no longer conforms to "standard" HTML blocks. The </li> would through razor for a loop, but because it's wrapped in <text></text> it has a more definitive way of knowing where code ends and HTML begins.
3) Yes, the parenthesis are there to help give the parser an explicit definition of what should be executed. Razor makes its best attempt to understand what you're trying to output, but sometimes it's off. The parenthesis solve this. e.g.
#Foo.bar
If you only had #Foo defined as a string, Razor would inevitably try to look for a bar property because it follows C#'s naming convention (this would be a very valid notation in C#, but not our intent). So, to avoid it from continuing on we can use parenthesis:
#(Foo).bar
A notable exception to this is when there is a single trailing period. e.g.
Hello, #name.
The Razor parser realizes nothing valid (in terms of the language) follows, so it just outputs name and a period thereafter.
4) ## is the escape method for razor when you need to actually print #. So, in your example, you'd see #foo on the page in plain text. This is useful when outputting email addresses directly on the page, e.g.
bchristie##contoso.com
Now razor won't look for a contoso.com variable.
5) You're seeing various shortcuts and usages of how you bounce between valid C# code and HTML. Remember that you can go between, and the HTML you're seeing is really just a compiled IHtmlString that is finally output to the buffer.
1.
By default, Razor automatically html-encodes your output values (<div> becomes <div>). #Html.Raw should be used when you explicitly want to output the value as-is without any encoding (very common for outputting JSON strings in the middle of a <script>).
2.
The purpose of <text> and #: is to escape the regular Razor syntax flow and output literal text values. for example:
// i just want to print "Haz It" if some condition is true
#if (Model.HasSomething) { Haz It } // syntax error
#if (Model.HasSomething) { <text>Haz It</text> } // just fine
As of #:, it begins a text literal until the next line-feed (enter), so:
#if (Model.HasSomething) { #:Haz It } // syntax error, no closing '}' encountered
// just fine
#if (Model.HasSomething)
{
#:Haz It
}
3.
By default, if your # is inside a quote/double-quotes (<tr id="row#item.Id"), Razor interprets it as a literal and will not try to parse it as expression (for obvious reasons), but sometimes you do want it to, then you simply write <tr id="row#(item.Id").
4.
The purpose of ## is simply to escape '#'. when you want to output '#' and don't want Razor to interpret is as an expression. then in your case ##foo would print '#foo'.
5.
a. #(MyClass.MyMethod<AType>()) would simply output the return value of the method (using ToString() if necessary).
b. Yes, Razor does let you define some kind of inline functions, but usually you better use Html Helpers / Functions / DisplayTemplates (as follows).
c. See above.
6.
As of Razor Helpers, see http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

Trying to access an images .source information in actionscript - for some reason it doesn't show up

I'm working on a project (using flash builder 4.5) where a user can click on one of a number of pictures to perform an action. The images are all loaded into an array of UIComponents through actionscript.
I have a private variable as follows:
private var _selectedChild:UIComponent;
Which keeps track of which UIComponent is currently "selected" (was the last item clicked).
I just want to show an Alert when the picture is clicked displaying it's id and the source filename.
Alert.show("Current id: " + _selectedChild.id + " -- filename: " + _selectedChild.source);
The id comes out easy with _selectedChild.id, but there is no such thing as .source - I looked throughout the entire list of possible variables eclipse gives me and I can't figure out which one would display the url or the source. I feel like I might be missing something easy - does anyone know how to get this information from a UIComponent?
This is the relevant mxml:
<dp:Test id="test" width="100%" height="100%" >
<mx:Image id="i1" source="images/i1.jpg"/>
<mx:Image id="i2" source="images/i2.jpg"/>
</dp:Test>
Any help is much appreciated.
You are casting an mx:Image object to the base UIComponent, which does not have property "source". Either leave _selectedChild as an ambiguous, *, type, or define it as mx.controls.Image. If you switch to spark, use spark.components.Image.
Alternativly, to be safe while using an ambiguous type, you can perform a check based for the property:
if(_selectedChild.hasOwnProperty("source"))
{
// do stuff
}
If I understand your code correctly, you need to cast the UIComponent to an Image first:
var image:Image = _selectedChild as Image;
if (!image) trace("Nothing selected or the child is not an image");
Alert.show("Current id: " + image.id + " -- filename: " + image.source);

will asp.net mvc model binder keep a posted array in the proper order?

so i've got an array of numbers that i'm posting to an asp.net mvc action that has a list(of integer) parameter and it all works great.
my question is this:
Is it safe to assume that the list(of integer) will have the numbers in the same order as they were in the array i posted?
Thanks for your time!
EDIT:
The data being posted looks like this:
POSTDATA=model.LevelIds=6&model.LevelIds=19&model.LevelIds=16&model.LevelIds=21&model.LevelIds=18
I'm using the Tamper Data firefox add on to see it.
I'm using jQuery, in traditional mode.
EDIT:
the action looks something like this:
public function Create(byval model as thecreateviewmodel) as actionresult
the thecreatviewmodel has a bunch of properties, but the interesting one is...
Public Property LevelIdsAs IList(Of Integer) = New List(Of Integer)
on the client side the view model is build with javascript/jquery:
function NewEntityDataBuilder() {
var theData = {
'model.Name' : $('#Name').val(),
'model.Description' : $('#Description').val(),
'model.LevelIds' : $('#LevelIds').val()
};
return theData;
}
that function is called from this bit of javascript which basically goes through the and adds all of the things in the list to a drop down list (select control) and selects them all.
$('#LevelIds').empty();
$('#AddedLevels').children().each(function () {
$('#LevelIds').append("<option value='" + $(this).attr('LevelId') + "'>" + $(this).attr('LevelId') + "</option>");
});
$('#LevelIds').children().attr('selected', 'selected'); //select all the options so they get posted.
var dataToPost = NewEntityDataBuilder();
this seems fairly convoluted when it's put this way, but it's actually fairly simple. it's all part of 2 connected drag and drop lists that are part of a form.
so: if i put the value of a select list with all of it's options selected in a variable and post that to an ilist(of integer) will ilist have them in the same order as they were in the select. It SEEMS like they are. but is that just a coincidence?
Usually the index is part of the parameter name:
ints[0]=0&ints[2]=2&ints[1]=1
And if you have a controller action that looks like this:
public ActionResult Index(List<int> ints)
{
// ints[0] = 0
// ints[1] = 1
// ints[2] = 2
return View();
}
UPDATE:
Let's suppose that you have multiple parameters with the same name in the query string. This query string will be parsed by the ASP.NET engine by the native HttpRequest object be convert into a NameValueCollection and more precisely a custom implementation called HttpValueCollection. This class is internal to ASP.NET which means that it is not documented and it might change with versions of .NET. Looking at it with Reflector there is the FillFromString and the way it is implemented it seems to preserve the order. But this is something I wouldn't rely on.

Resources