passing anonymous object to view - asp.net-mvc

I want to pass two values from controller action to asp.net MVC 3 Razor view. I am doing like this in action method:
var model = new { reportid = rid, refno = refernumber};
return View(model );
but when i try to access it in view like this:
#Model.reportid
I get, object doesn't contain property reportid
How can I pass multiple values without using viewbag ?

Well, i strongly recommend you to use ViewModel class. But if for some reason you have phobia of extra viewmodel classes, you can use C# feature called Tuple
var model = Tuple.Create(firstObject, secondObject)
and then your view will be of type Tuple, for example
#model Tuple<int, string>
and you can access them like this
#Model.Item1
And then you can congratulate yourself, you have achieved nice mess with hidden meaning :)

Another way to accomplish this task - is to use ExpandoObject.
dynamic model = new System.Dynamic.ExpandoObject();
model.reportid = 123
model.refno = 456;
Set the view model type to dynamic:
#model dynamic
#Model.reportid
#Model.refno

Related

DropDownList in my edit view mvc

i have List view and in every rows it has the "Actualizar" link action and that one takes me to the edit view in which i have some dropdownLists available for updating my existing data but my big problem is that i want the dropdownlist to first load the data is save. how can i set the dropdownlist to load the data of the model a return and let me choose other options
controller:
public ActionResult ActualizarDispositivo(int id )
{
dropDown();
var equipo= _db.equipo.Include(m=>m.marca).Include(mo=>mo.modelo.Single(b => b.idEquipo==id);
ViewBag.idMarca = _db.marca.ToList().Select(Mar => new SelectListItem
{
Value = Mar.idMarca.ToString(),
Text = Mar.Descripcion.ToString(),
Selected = true
});
return View("ActualizarDispositivo",equipo);
}
in the edit view i have this
#Html.DropDownListFor(m=>m.idMarca,(IEnumerable<SelectListItem>)ViewBag.idMarca)
The code you are using should work, if you simply remove the Selected = true. Currently you are setting all of the DropDownList's values to selected.
I'm not sure which performs better, but I do find it more readable to create a select list using:
ViewBag.idMarca = new SelectList(_db.marca.ToList(), "idMarca", "Descripcion");
And then, there may be no need to cast. (Unsure, I avoid the use of ViewBag)
#Html.DropDownListFor(m=>m.idMarca, ViewBag.idMarca)

Is it possible to dynamically set selectedvalue using dropdownlistfor with nested classes?

I have a class, Farm, which contains a list of classes of type Animal.
public class Farm {
public list<Animal> Animals;
// other members..
}
public class Animal {
public string Name;
public string Family;
}
I would like to make a createOrEdit view for my Farm object, and I'd like to use DropDownLists for the Animal's Name and Family. The choices are coming from a database.
When I pass the Animal model to the view for editing I'd like to have the DropDownLists somehow match the properties for each animal and set the selected values of the lists.
I've tried lots of things like this:
#for(int i = 0; i < Model.Animals.Count; i++)
{
#Html.DropDownListFor(model => model.Animals[i].Name, Model.AnimalNames)
// where Model.AnimalNames is a SelectList
#Model.Animals[i].Name // (for testing) this properly displays the name I want to be selected in the list
}
I've seen a bunch of suggestions on this site for creating SelectLists in the controller, iterating through each item and setting the selected property where appropriate. But there's gotta be a cleaner way.. what if I have 100 Animals on my farm. It doesn't seem reasonable to create 200 SelectLists in the controller, iterate through each of them to match up the selected values, and then pass that to the view.
So, is there a simple way for me to take that Animal.Name[i] value and find its matching listitem in the DDL?
Thanks!!
Inside your foreach loop you can do:
#for(int i = 0; i < Model.Animals.Count; i++)
{
var original = Model.AnimalNames;
var animalSelected = new SelectList(original.Items, original.DataValueField, original.DataTextField, model.Animals[i].Name);
#Html.DropDownListFor(model => model.Animals[i].Name, animalSelected)
}
This way, in your controller you create just one SelectList with the AnimalNames... and in your view, you create SelectList with the selected value for each one.
We use this approach when using list of editable items with the need of display the current value of each item.

MultiSelectList SelectedValues, not working in mvc3

Debugging I get this:
So, User_SportsList is a MultiSelectList with the proper Items and the proper SelectedValues.
I pass to the view like this:
ViewBag.usl = User_SportsList;
In my View I have this:
#Html.ListBox("UserSports", ViewBag.usl as MultiSelectList)
And is showing the list with all the items, but SelectedValues aren't working. What I'm doing wrong ?
The SelectedValues property needs to contain an array of values (where "value" is defined by DataValueField), and not the items themselves. So, in this example, you should set SelectedValues equal to:
User_SportsList.SelectedValues = new [] { 3, 4 };

Extracting [] elements from form collection - mvc - should use icollection but have mix of types

have looked at Phil Haacks project on books at
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
which has been useful, but I have a mix of data types.
I use a modelview so that i can have a mix of objects, in this case: Order (ie order.id, order.date etc), Customer, SoilSamplingOrder and a list of SoilSamplingSubJobs which is like this [0].id, [0].field, [1].id, [1].field etc
Perhaps I should be using ICollection instead of List? I had problems getting UpdateModel to work so I used an extract from collection method. the first 4 method calls : orderRepository.FindOrder(id); etc give the model the original to be edited. but after this point i'm a little lost in how to update the subjobs. I hope i have delineated enough to make sense of the problem.
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Order order = orderRepository.FindOrder(id);
Customer cust = orderRepository.FindCustomer(order.customer_id);
IList<SoilSamplingSubJob> sssj = orderRepository.FindSubOrders(id);
SoilSamplingOrder sso = orderRepository.FindSoilSampleOrder(id);
try
{
UpdateModel(order, collection.ToValueProvider());
UpdateModel(cust, collection.ToValueProvider());
UpdateModel(sso, collection.ToValueProvider());
IList<SoilSamplingSubJob> sssjs = orderRepository.extractSSSJ(collection);
foreach (var sj in sssjs)
UpdateModel(sso, collection.ToValueProvider());
orderRepository.Save();
return RedirectToAction("Details", new { id=order.order_id});
}
catch
{
return View();
}
}
I think you should work on developing a view model that reflects the data that you need to get back and create display/edit templates for that model that renders the view model using Phil Haack's methods for your lists of objects -- in this case, arrays of submodel classes. Let the model binding framework build the returned model (as a parameter) to your action, then reconstitute your domain models from the view model data. Brad Wilson has an excellent series of articles on templating that should be helpful.
I use IModelBinder on my complex classes. You don't need IModelBinder, but it will make your controller post codeblock look much cleaner. I'm using VB at the moment, but my class looks something like this for example:
Public Class CombinedRulesAndXmlRules : Implements IModelBinder
Public Rules As New Rules()
Public XmlRules As New XmlRules()
Public RequiredTemplates As New List(Of RequiredTemplates)
Public SearchCriteria As New List(Of SearchCriteriaList)
Public OptionalTemplates As New List(Of OptionalTemplates)
Public Questions As New List(Of Questions)
Public QATemplates As New List(Of QATemplates)
**Public Answers As New List(Of Answers)**
Now I don't use editor templates in my views, so to have your lists appear in the formcollection you have to add something like this in your view:
#For x As Integer = 0 To Model.Answers.Count - 1
Dim incr As Integer = x
#Html.HiddenFor(Function(model) model.Answers(incr).Answer)
#Html.HiddenFor(Function(model) model.Answers(incr).AnswerId)
#Html.HiddenFor(Function(model) model.Answers(incr).AnswerTemplateTag)
#Html.HiddenFor(Function(model) model.Answers(incr).Tag)
Next
When the view is submitted/posted, the model binder takes over before hitting the first line of code in your mvc post controller method. I then iterate through the actual formcollection and strip out the [#] using regex, because your formcollection will show your list items like this: Answers[0].Answer, Answers[0]AnswerId ,etc.:
For x As Integer = 1 To request.Form.Count - 1
keyname = request.Form.Keys(x)
Debug.Write(keyname)
val = request.Form(x).ToString()
'If keyname contains [#] strip it. it's a list item.
Dim pattern As String = "\[(\d+)\]"
Dim iterpattern As String = "\d+"
Dim rgx As New Regex(pattern)
Dim rgxiter As New Regex(iterpattern)
If Regex.IsMatch(keyname, pattern) Then
Dim match As Match = rgxiter.Match(keyname)
ListIteration = CInt(match.Value)
Dim result As String = rgx.Replace(keyname, "")
keyname = result
End If
The Select Case codeblock is next. So you already know you have a strong typed class in your model, so your select can look like this:
Select Case keyname
Case "Answers.Answer"
'add code here to add to your return list. What you
'get in the post controller is a fully populated class.

Entity Framework - Select specific columns and return strongly typed without losing cast

I'm trying to do something similar to this post where I don't pull back all columns from a particular entity, however my framework makes use of inheritence and I lose scope of the entity type after it's been cast to an anonymous type.
The structure of my Entity Framework has a base entity called Action. From here I've created two inherited entities called Event and Activity. I want to pull back the last X Actions and pass them to my strongly typed view which accepts an Action and from there determines if its an Activity or Event and renders the correct partial view.
if(Model.GetType() == typeof(Event))
{
//render Event view
}
else if(Model.GetType() == typeof(Activity))
{
//render Activity view
}
I can pull the last 10 as an anonymous type and then cast:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
select new { a.CreatedOn, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => new Action {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}).ToList();
However, once I pass the new List of Actions to my strongly typed view it loses scope of whether it's an Activity or an Event since it's been cast as an Action. My question is, without exposing the discriminator column, is there any way to cast each item to the proper type or am I going about this the wrong way?
A bit kludgy, but will work:
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let IsEvent = a as Event != null
select new { a.CreatedOn, IsEvent, a.Summary };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary
}
}).ToList();
Example with type-specific columns, presuming that e.EventSpecific is of a nullable type.
var result = from a in new DataContext().Actions
where a.UserId == someGuidValue
let ev = a as Event
let IsEvent = ev != null
select new { a.CreatedOn, IsEvent, a.Summary, ev.EventSpecific };
List<Action> list = result.AsEnumerable()
.Select(o => o.IsEvent ?
(Action) new Event {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific
}
: (Action) new Activity {
CreatedOn = o.CreatedOn,
Summary = o.Summary,
EventSpecific = o.EventSpecific // will be null, but using o.EventSpecific saves casting
}
}).ToList();
If o.EventSpecific is of a non-nullable type, then you must convert it to a nullable type in the L2E query.
You are probably on the wrong way. At first I would assume that Action should be an abstract class and you should not be able to create instances of it at all. If you then only fetch a subset of the properties and the subset does no longer allow to discriminate between events and activities, it is probably the wrong way to try making events and activities out of them.
So it actually seems not to be a technical problem - it should be quite easy to include some discrimination information in the anonymous type - but a design problem. I suggest to rethink if it is required to discriminate the query result and if so if it is really a good idea to discriminate the result in absence of an discriminator.

Resources