How can I get access to a variable in a View which was created in a Controller? - asp.net-mvc-3

How can I get access to a variable in a View which was created in a Controller?

Either put the variable into the Model that you are using for your View
Or use a ViewBag variable - e.g. from http://weblogs.asp.net/hajan/archive/2010/12/11/viewbag-dynamic-in-asp-net-mvc-3-rc-2.aspx
public ActionResult Index()
{
List<string> colors = new List<string>();
colors.Add("red");
colors.Add("green");
colors.Add("blue");
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
and
<p>
My name is
<b><%: ViewBag.Name %></b>,
<b><%: ViewBag.Age %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewBag.ListColors) { %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
although hopefully you'll be using Razor :)

You need to send the variable to the view in the ViewModel (the parameter to the View() method) or the TempData dictionary.

You can add it to the ViewData[] dictionary or the (newer) ViewBag dynamic.
In your controller:
ViewData['YourVariable'] = yourVariable;
// or
ViewBag.YourVariable = yourVariable;
In your view:
<%: ViewData["yourVariable"] %>
// or
<%: ViewBag.YourVariable %>

Related

Send parameter from Spring MVC controller to jsp code

I'm trying to send the variable average review from controller to view and show a number of stars equal with average review.
The problem is that I don't know how to loop through received variable and java code doesn't recognize that variable. I tried with a foreach from JSTL, but there is no list of objects; I want a classic for loop.
Here is my controller:
#RequestMapping(value = "/viewDetails", method = RequestMethod.GET)
public ModelAndView viewProductDetails(HttpServletRequest request) {
int productID = Integer.parseInt(request.getParameter("id"));
// irrelevant code goes here
double averageReview= reviewDAO.getAverageReview(productID);
modelAndView.addObject("averageReview",averageReview);
return modelAndView;
}
This is my view page, where I tried to loop:
<p>
<c:set var = "averageReview" scope = "session" value ="${averageReview}"/>
<% for(int i=0;i< ${averageReview}; i++){ %>
<span class="glyphicon glyphicon-star"></span>
<% } %>
</p>
How about this?
<c:forEach var = "i" begin = "0" end = "${averageReview}">
<span class="glyphicon glyphicon-star"></span>
</c:forEach>

Silverstripe Sessions or URL Parameters

I'm trying to figure out how to pass a value from my .ss page to my controller for a custom search filter that I've built. The idea is you click on this image or a form button and then the page will set a session variable and refresh itself. Upon page load the page loads different information depending on what it reads in the session variable. I can accomplish the same thing with URL Parameters but there are no examples online that I could find that would show me how to do this.
Basically I have this as my php:
class ArticleHolder_Controller extends Page_Controller {
public function ValidateType(){
if(isset($_SESSION['mySearchTag']) && !empty($_SESSION['mySearchTag'])) {
$tag = $_SESSION['mySearchTag'];
}
else{
$tag='News';
}
$filter = $this::get()->filter('Filters:PartialMatch', $tag)->First();
if ($filter == NULL){
return NULL;
}
else{
$_SESSION['mySearchTag']=$tag;
return $this->PaginatedPages();
}
}
public function PaginatedPages(){
$paginatedItems = new PaginatedList($this->filterArticles($_SESSION['mySearchTag']), $this->request);
$paginatedItems->setPageLength(3);
return $paginatedItems;
}
public function filterArticles($tag){
return ArticlePage::get()->filter('category:PartialMatch', $tag)->sort('Date DESC');
}
}
my .ss looks like this:
<% if ValidateType() %>
<ul>
<% loop $PaginatedPages %>
<li>
<div class="article">
<h2>$Title</h2>
<h3>$Date</h3>
<img class="indent" src="$Photo.link" alt="image"/>
<p class="indent">$Teaser</p>
</div>
</li>
<% end_loop %>
</ul>
<% include Pagination %>
<% else %>
<p>SORRY NO RESULTS WERE FOUND</p>
<% end_if %>
This code works as is. What I cannot figure out how to now add a clickable button on .ss page that will reload the page and set a session variable value.
If I can achieve this with url parameters then that can work too, I just need to know how to set them in the .ss page and how to retrieve them in the php.
Create a SetFilter function that will take the URL parameter ID and set it to your session variable:
public function SetFilter() {
if($this->request->param('ID')) {
$_SESSION['mySearchTag'] = $this->request->param('ID');
}
return array();
}
Make sure your SetFilter function is added to the $allowed_actions of your controller:
static $allowed_actions = array (
'SetFilter'
);
This function is called by your page link followed by /SetFilter/[your-filter].
In your template you would create a link to create this filter like so:
Filter articles by example

Best way to pass single value from view to controller

I have a form that posts a single value, but I cant seem to get it to the controller. I have verified the value exists in the form, but it arrives at the controller as null. Here is the form post:
<%Html.BeginForm("SaveRecord", "NewApplicant", FormMethod.Post, new { id = Model.PersonModel.ApplicantID } ); %>
<%: Html.Hidden("NewId", Model.PersonModel.ApplicantID) %>
<input type="submit" class="SKButton" value="Save" title="Save this new application as a unique record." />
<% Html.EndForm(); %>
and here is the contoller action:
public ActionResult SaveRecord(NewApplicantViewModel model)
{
int NewAppId = model.PersonModel.ApplicantID;
I have also tried:
public ActionResult SaveRecord(int NewId)
{
model.PersonModel.ApplicantID = NewId;
These must be a simple fix, and I want to pass the id in the model, dont want to use ajax. Thoughts?
Try using:
<%: Html.HiddenFor(model => model.PersonModel.ApplicantID) %>

MVC3 Master-Details Validation not Displaying

I have an MVC3 page with an object (Header) that has data and a list of objects (Details) that I want to update on a single page. On the details object I have custom validation (IValidatableObject) that also needs to run.
This appears to generally be working as expected, validations are running and returning ValidationResults and if I put an #Html.ValidationSummary(false); on the page it displays those validations. However I don't want a list of validations at the top, but rather next to the item being validated i.e. Html.ValidationMessageFor which is on the page, but not displaying the relevant message. Is there something I'm missing? This is working on other pages (that don't have this Master-Details situation), so i'm thinking it is something about how I'm going about setting up the list of items to be updated or the editor template for the item?
Edit.cshtml (the Header-Details edit view)
#foreach (var d in Model.Details.OrderBy(d => d.DetailId))
{
#Html.EditorFor(item => d, "Detail")
}
Detail.ascx (the Details Editor Template)
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Detail>" %>
<tr>
<td>
<%= Model.Name %>
<%= Html.HiddenFor(model => model.DetailId) %>
</td>
<td class="colDescription">
<%= Html.EditorFor(model => model.Description) %>
<%= Html.ValidationMessageFor(model => model.Description) %>
</td>
<td class="colAmount">
<%= Html.EditorFor(model => model.Amount) %>
<%= Html.ValidationMessageFor(model => model.Amount) %>
</td>
</tr>
Model is Entity Framework with Header that has Name and HeaderId and Detail has DetailId, HeaderId, Description and Amount
Controller Code:
public ActionResult Edit(Header header, FormCollection formCollection)
{
if (formCollection["saveButton"] != null)
{
header = this.ProcessFormCollectionHeader(header, formCollection);
if (ModelState.IsValid)
{
return new RedirectResult("~/saveNotification");
}
else
{
return View("Edit", header);
}
}
else
{
return View("Edit", header);
}
}
[I know controller code can be cleaned up a bit, just at this state as a result of trying to determine what is occuring here]
IValidatableObject implementation:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.Name.Length < 5) && (this.Amount > 10))
{
yield return new ValidationResult("Item must have sensible name to have Amount larger than 10.", new[] { "Amount" });
}
}
I would recommend you to use real editor templates. The problem with your code is that you are writing a foreach loop inside your view to render the template which generates wrong names for the corresponding input fields. I guess that's the reason why you are doing some workarounds in your controller action to populate the model (header = this.ProcessFormCollectionHeader(header, formCollection);) instead of simply using the model binder to do the job.
So let me show you the correct way to achieve that.
Model:
public class Header
{
public IEnumerable<Detail> Details { get; set; }
}
public class Detail : IValidatableObject
{
public int DetailId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Amount { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if ((this.Name ?? string.Empty).Length < 5 && this.Amount > 10)
{
yield return new ValidationResult(
"Item must have sensible name to have Amount larger than 10.",
new[] { "Amount" }
);
}
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new Header
{
Details = Enumerable.Range(1, 5).Select(x => new Detail
{
DetailId = x,
Name = "n" + x,
Amount = 50
}).OrderBy(d => d.DetailId)
};
return View(model);
}
[HttpPost]
public ActionResult Index(Header model)
{
if (ModelState.IsValid)
{
return Redirect("~/saveNotification");
}
return View(model);
}
}
View (~/Views/Home/Index.cshtml):
#model Header
#using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
#Html.EditorFor(x => x.Details)
</tbody>
</table>
<button type="submit">OK</button>
}
Editor template for the Detail type (~/Views/Shared/EditorTemplates/Detail.ascx or ~/Views/Shared/EditorTemplates/Detail.cshtml for Razor):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<MvcApplication1.Controllers.Detail>"
%>
<tr>
<td>
<%= Html.DisplayFor(model => model.Name) %>
<%= Html.HiddenFor(model => model.DetailId) %>
<%= Html.HiddenFor(model => model.Name) %>
</td>
<td class="colDescription">
<%= Html.EditorFor(model => model.Description) %>
<%= Html.ValidationMessageFor(model => model.Description) %>
</td>
<td class="colAmount">
<%= Html.EditorFor(model => model.Amount) %>
<%= Html.ValidationMessageFor(model => model.Amount) %>
</td>
</tr>
Here are a couple of things that I did to improve your code:
I performed the ordering of the Details collection by DetailId at the controller level. It's the controller's responsibility to prepare the view model for display. The view should not be doing this ordering. All that the view should do is display the data
Thanks to the previous improvement I git rid of the foreach loop in the view that you were using to render the editor template and replaced it with a single #Html.EditorFor(x => x.Details) call. The way this works is that ASP.NET MVC detects that Details is a collection property (of type IEnumerable<Detail>) and it will automatically look for a custom editor templated inside the ~/Views/SomeController/EditorTemplates or ~/Views/Shared/EditorTemplates folders called Detail.ascx or Detail.cshtml (same name as the type of the collection). It will then render this template for each element of the collection so that you don't need to worry about it
Thanks to the previous improvement, inside the [HttpPost] action you no longer need any ProcessFormCollectionHeader hacks. The header action argument will be correctly bound from the request data by the model binder
Inside the Detail.ascx template I have replaced <%= Model.Name %> with <%= Html.DisplayFor(model => model.Name) %> in order to properly HTML encode the output and fill the XSS hole that was open on your site.
Inside the Validate method I ensured that the Name property is not null before testing against its length. By the way in your example you only had an input field for the Description field inside the template and didn't have a corresponding input field for the Name property, so when the form is submitted this property will always be null. As a consequence I have added a corresponding hidden input field for it.

ASP.Net MVC ViewData Issue

I have the following code:
private Models.mediamanagerEntities dataModel = new Models.mediamanagerEntities();
public ActionResult Index(FormCollection form)
{
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
return View();
}
View:
%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<Project_Name.Models.Item>>" %>
<% foreach (var m in ViewData.Model)
{ %>
Title: <%= m.Title %>
<% } %>
I get the following error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[System.Data.Objects.DataClasses.EntityCollection1[Project_Name.Models.Item]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Project_Name.Models.Item].
I'm not too sure what it happening here or how to rectify it, Thanks.
Your LINQ is creating a list like this List<EntityCollection<Item>>, when your view wants List<Item>.
I don't know query syntax for LINQ very well, but this is how you'd get what you want with function syntax:
ViewData.Model = dataModel.Customers.SelectMany(c => c.Type.Items).ToList();
That will take the many Items under each customer and flatten them into one list of Items.
Replace this line:
ViewData.Model = (from m in dataModel.Customers select m.Type.Items).ToList();
with the following:
ViewData.Model = dataModel.Type.ToList();

Resources