how to access a ModelAndView object within the jsp page - spring-mvc

I have a code like this in my controller.
ModelAndView result = new ModelAndView("person/sometrends");
result.addObject("data", data); // data -> Map
In my JSP page I have written some Java code that is dependent on the data object.
How can I get that data object within the JSP code?
I tried something like this (pseudo code).
<%
Map x = ${data};
%>
But that doesn't work. Not sure how to access it.

In a scriptlet, you use the request object like so:
<% Map myMap = (Map) request.getAttribute("data"); %>
If you want to use something like JSTL instead of a scriptlet, you could do:
<c:forEach var="entry" items="${data}">
Name: ${entry.key} <br/>
Value: ${entry.value} <br/>
</c:forEach>
As Davemeister and novice pointed out, combining EL inside a scriptlet was the root cause of your error.

Let me more specific, if you want to use jsp instead of jstl to access the Model you would do something like this:
<% Map x = (Map)request.getAttribute("data") %>

Try this:
request.getAttribute("data")

try<% String username = (String)request.getAttribute("data"); %>

Using expression language inside the scriptlet would be the cause.

include: <%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
and then...
<%
Map x = ${data};
%>

Related

Switching between two Eval values on the asp.net front end page

Developers, I am in need of providing different
<%# Eval("variable") %>
For my Grid. I have requirements that require me to either show StagingDB Data or ProdDB Data per Eval
Pseudocode
<%# If Eval("isDraft) ? Eval("tbl_staging_value") : Eval("tbl_value") %>
Stackoverflowers... You are my only hope... Thanks. Working on Sunday...
You can use ?: operator.
<%# Convert.ToBoolean(Eval("isDraft")) ? Eval("tbl_staging_value"):
Eval("tbl_value") %>
By creating a new property on your data source
public string tbl_val
{
get
{
return isDraft ? tbl_staging_value : tbl_value;
}
}
you can simplify the data binding
<%# Eval("tbl_val") %>

Print code behind function return value in aspx page

I'm sure this is trivial, but why isn't the Windows Authentication user printing in my ASP.NET page inline?
Code behind function:
public string GetCurrentUserWindowsLogin()
{
string windowsLogin = Page.User.Identity.Name;
int hasDomain = windowsLogin.IndexOf(#"\");
if (hasDomain > 0)
{
windowsLogin = windowsLogin.Remove(0, hasDomain + 1);
}
return windowsLogin;
}
Inline code:
<div class="loginDisplay">[ <%#GetCurrentUserWindowsLogin() %> ]</div>
The <%#... %> is used for Binding Expressions like Eval and Bind.
So if you call Page.DataBind() in page_load it should work.
Another way that should work is to use code render blocks which run normal code:
<% GetCurrentUserWindowsLogin() %>
or the <%= %> construct used for small chunks of information:
<%= GetCurrentUserWindowsLogin() %>
Just a follow up on the above answer, the <%= is like response.write.
http://msdn.microsoft.com/en-us/library/vstudio/6dwsdcf5(v=vs.100).aspx

Dynamically add items to a collection in MVC2 using EditorFor()

I'm trying to do this: Editing a variable length list, ASP.NET MVC 2-style
In the post he mentions that it could be done with less code using Html.EditorFor(), but that it would be more difficult because of the indexes. Well, that's exactly what I want to do, and I don't know where to begin.
I'm an ASP.NET novice who just completed the Nerd Dinner tutorial before jumping into a project at work, so any help would be appreciated.
Update 1: Instead of generating a GUID for each item in the collection, I'd like to generate incremental indexes starting with 0. Right now the field names look like "gifts[GUID].value"; I would like them to be "gifts[0].value","gifts1.value" etc. but I don't understand how the collection keeps track and generates these indices.
In response to your update about generating indexes instead of GUIDs, the original linked article had a few comments from others that tried to solve the same issue but none of them worked for me. What I found was the collection with index was referenced in the following location:
html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix
So I wrote a helper function to parse out the index (and if there is a problem then the GUID would be generated)
public static string GetCollectionItemIndex(this HtmlHelper html, string collectionName)
{
int idx;
string sIdx;
if (Int32.TryParse(Regex.Match(html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix, #"\d+").Value, out idx))
{
sIdx = idx.ToString();
}
else
{
sIdx = Guid.NewGuid().ToString();
}
return sIdx;
}
I edited the BeginCollectionItem(..) function to call this helper function when setting the item index:
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : GetCollectionItemIndex(html, collectionName);
Hope this helps someone else!
Well, you begin by defining an editor template (~/Views/Shared/EditorTemplates/Gift.ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.Gift>" %>
<div class="editorRow">
<% using(Html.BeginCollectionItem("gifts")) { %>
Item: <%= Html.TextBoxFor(x => x.Name) %>
Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %>
<% } %>
</div>
And then replace the RenderPartial call with EditorForModel:
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<%= Html.EditorForModel() %>
</div>
<input type="submit" value="Finished" />
<% } %>
Once you've tried this you may come back and ask if you have any problems by explaining the symptoms.

All controls are still null after calling EnsureChildControls()?

The way this page is laid out, all of the data is loaded at Page_Init. Well, I have a custom control that is having problems with this though.
I have it on the page like so:
<cc:SomeControl... />
And then I set the value at Page_Init using
MyControl.Value="blah";
Simple stuff..
The Value is an accessor and has something similar to this:
public string Value{
get...
set{
EnsureChildControls();
MyHiddenField.Value=value;
}
}
and it is here that I have a problem. It says that MyHiddenField is null. Is Page_Init just too early for this? Or is there some other function I need to call?
The fix for this was changing from using a namespace to reference the CustomControl to using a src with a filename
changing this:
<%# Register Assembly="MyProduct" Namespace="MyProduct.CustomControls" TagPrefix="cc" %>
to this:
<%# Register src="/CustomControls/MyControl.ascx" tagname="MyControl" tagprefix="uc2" %>

asp.net mvc user control problem foreach loop

Previous post
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
MvcApplication1.Models.FeaturesRepository _model = new MvcApplication1.Models.FeaturesRepository();
%>
<% foreach (var md in _model.GetAllFeatures())
{ %>
<li><%= md.vcr_FeaturesName %></li>
<% } %>
It is with reference to the previous post above.Is there something wrong with the foreach loop(The result is correct but it is displaying the series of Add,Add,Add,Add,Add,Add...,which is the last record of the getallfeatures.
#mazhar, instead of creating your model like you are, in MVC you should return the model to the view.
In your controller you would say something like return View(MyModel);
I don't see anything wrong, per-sey, with your foreach but if you are going to replicate a control over and over you may want to consider a PartialView and rendering that by passing the appropriate model to it.
<% foreach ( var md in model.features ) Html.RenderPartial(md); %>
The above is untested but close I think.
I haven't looked at the previous post because I think you need to get this into the MVC way first. I don't think there is technically anything incorrect in your code and suspect it's your controller and model code.
I've edited your post to remove the commented out code. Very confusing leaving it in.

Resources