ASP.NET MVC 2 Without Data Model Query - asp.net-mvc

Can anyone tell me how to use ASP.NET MVC 2 without data models...i mean i have sql database and stored procedure which has employyes table i wanna show all employees list on a View without using any data model.

You can have your controller do the sql query, generate a List of something, then pass the list to the view using ViewData. This however is a deformation of the MVC model...

I see two solutions.. one is ugly, but it's probably what your'e looking for. In your controller you can use your procedure to get data, and then pass it to the view using ViewData collection, f.e:
public ActionResult Details(int id)
{
var intData = SPGetInt(id);
var stringData = SPGetString(id);
ViewData["intData"] = intData;
ViewData["stringData"] = stringData;
return View();
}
and then use it like:
<%=ViewData["intData"] %>
The better solution is to create at least an ViewModel, just to hold the informations you need to display. You can rewrite all data you get from DB to that model. Then you will get very important feature which is strongly typed view.

Related

MVC: Correct way to bind DropDownList

I need to create a form to insert an Author. In that form, there will be a DropDownList for AuthorCategory. Both Author and AuthorCategory are model classes.
I created a ViewModel just for the relevant fields of creating an author, which have public properties of FullName, Email and IEnumerable. AuthorCategories will have to be pulled from the Database hence my question is:
Which way is the correct way of binding the dropdown with the categories;
1: Have the controller action to populate the data and pass the viewmodel to the view
2: Have the relevant property in the ViewModel getter access db and return a list such as:
public List<AuthorCategory> Categories
{
get
{
using (DAL.AdminDbContext db = new DAL.AdminDbContext())
{
return new List<AuthorCategory>(db.AuthorCategories.ToList());
}
}
}
3: Directly access the db from the View
4: ViewBag / ViewData?
5: Use AutoMapper?
How this is generally handled? Any ideas would be appreciated.
I would recommend using your ViewModel as a dummy data transfer object, option#2 is excluded. The role of ViewModel is to transfer data needed for the View. Apart it is good to have Model that is mapped to you database table. So here comes Automapper as it simplifies getting ViewModel out of Model and vice versa. Controller retrieves data from DB into Model and ViewModel is populated say with Automapper.
Option #3 of directly accessing the db from the View is not a good idea. Such code will be hard to debug and test. No separation of concerns.
Option #4 of using ViewBag/ViewData for such purposes is not a good one. There are a lot of mechanisms in razor view engine that rely on #Model present in View.

How to display in View the Function Import Complex Result or Stored Procedure?

I am looking for help with MVC and the Entity Framework. I have imported a stored procedure into my Entity Framework and it returns a Collection of Complex Name_Results.
How do I go about calling the complex result and tying it to the View page? Using a normal table imported model,
I could iterate through the page and reference the model with
#model IEnumerable<Project.Models.ImportedTableName>
but when I say
#model IEnumerable<Project.Models.ComplexName_Result>
I get an error along the lines of
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Project.Models.ImportedTableName]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Project.Models.ComplexName_Result]'.
Any advice? Thank you ahead of time for your help!
You need to pass the correct model type to the view. Since your view is strongly typed to IEnumerable<Project.Models.ComplexName_Result> that's what you should pass to it from your controller action:
public ActionResult SomeAction()
{
IEnumerable<Project.Models.ComplexName_Result> model = ...
return View(model);
}

Completely not understanding View Data for MVC right now, need some serious help & code examples

I really need to maintain this string called "filterParams" in my MVC application. After the user enters some search parameters he clicks submit, and the grid is rebinded with that parameter. That works great. I also save the filterParams data in a Javascript variable, so when the user pages, and the OnDataBinding event is raised, the filter is also passed through that ajax call as well. this is all well and good however there is a huge issue, because when the user updates a question, all the results dissapear because it returns to the View and it does not have any data there. The way I'm using ViewData isn't working, and I could use your help, because if I can store it in ViewData and access it, it would fix my problems. I cannot use TempData because there are a number of other Actions that can be called in between Select and Update...Long question short, how do I implement ViewData correctly to store and retrieve a string in my controller?
Here are some code snippets.
[GridAction]
public ActionResult GetAllQuestion(string filterParams)
{
var _filterParams = new List<string>();
_filterParams.Add(filterParams);
ViewData["filterParams"] = _filterParams;
return View(new GridModel(QuestionManager.Instance.GetQuestion(filterParams)));
}
[GridAction]
public ActionResult EditQuestion(int id, QuestionDTO pQuestion)
{
// var _question = QuestionManager.Instance.GetQuestion(id,false).FirstOrDefault();
// TryUpdateModel(_question);
var _filterParams = (List<string>)ViewData["filterParams"];
var filterParams = _filterParams[0];
QuestionManager.Instance.UpdateQuestion(pQuestion);
// return View(new GridModel(QuestionManager.Instance.GetQuestion(id, false)));
return View(new GridModel(QuestionManager.Instance.GetQuestion(filterParams)));
}
in my aspx page
Html.Telerik().Grid<QuestionDTO>()
.DataBinding(dataBinding => dataBinding.Ajax().Select("GetAllQuestion", "Question", new { filterParams = string.Empty }).Update("EditQuestion", "Question").Insert("CreateQuestion", "Question"))
How can I get this to work please? Help is appreciated
ViewBag/ViewData only works for sending data from an action to a view. It does not get populated by the Model Binder when a request is made to an action, and its state is not saved between requests because ASP.net MVC is entirely stateless. In other words, the ViewData dictionary is always empty at the start of a request.
Meaning this line in your EditQuestion action will not work:
var _filterParams = (List<string>)ViewData["filterParams"];
ViewData is empty, so _filterParams will be null.
You have to manually send filterParams to the EditQuestion action just as you do for the GetAllQuestions action.
Perhaps a better alternative would simply be to persist filterParams using a temp cookie on the client side.
So, just to defy all the misinformation I've read on the subject, TempData infact does persist through multiple action calls in the controller and was able to be used to implement the functionality I needed.
Why just not store the data in Session?
Here's a good explanation with examples
http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

How do I get results from LINQ to SQL query to partial view?

I'm trying to get the following results from the Controler action method to the partial view. Typically I just use a model and reference at the top of the page. But I think 'results' is different because it is coming from the LINQ to SQL and don't know how to reference in the view so I can use it to iterate over the results to display.
[HttpGet]
public PartialViewResult SelectUnits()
{
var results = (from stats in db.t_harvest
orderby stats.unit_number
select new
{
stats.unit_number,
}).Distinct().ToList();
return PartialView(results);
}
You cannot use a strongly typed partial since the return list is of Anonymous Types (IE: new { ... }).
However, since you're returning only 1 value there's no need for it.
var results = (from stats in db.t_harvest
orderby stats.unit_number
select stats.unit_number).Distinct().ToList();
return PartialView(results);
So if unit_number is an int then make your partial views model an IEnumerable<int>.
In the case that you do need to send an anonymous type back, make your partial views model of type dynamic.
Just as a word of warning, be careful with dynamic (and ViewBag, which is also dynamic) since syntax errors (such as a type-o when accessing a property on it) will be caught at runtime instead of compile time. For this reason I personally prefer strongly typed views where applicable.
There are 3 ways you can pass data to your view:
ViewData["SomeName"] = 12345;
ViewBag.SomeName = 12345; // MVC3+
ViewData.Model = 12345; // Same as doing: return PartialView(12345);
This will return a list of anonymous objects, so one option is to access them using the dynamic object (ViewBag) that is already within each view (if you are using MVC3 that is)
Here is a good article on ViewBag and ViewData, where ViewData is just another way that you could pass this to the view.
This is rough and untested, but I believe this should work:
Controller.cs
ViewBag.Results = results;
return PartialView();
PartialView
#(foreach(var result in ViewBag.Results)
{
result.unit_number.ToString();//This line should print out the HTML
}
)

Need advice on how to structure asp mvc razor page

I have one page that will contain a lot data.
Outline of the page is on the image.
For output I have used "razor" engine.
Now I wonder will I get something if I refactor my code so each section
which data comes from database will be partial view?
On this page I need about 20 value objects to display all needed data.
I have made one "ViewModel" class that contains all data I need and set that
viewModel class as razor page model. Is this the right way how I should do this or
there is some smarter way?
public class MyViewModelClass{
public ValueObjectx x;
public ValueObjecty y;
public ValueObjectz z;
public List<ValueObjectT> tList;
public List<ValueObjectG> gList;
public List<ValueObjectS> sList;
}
In a scenario like this I would typically have each section as a partial view. Each section is responsible for it's own layout and ViewModel. This prevents the tendency to have a super view which has to know about too many things in order to render.
I would not use one ViewModel for all the data. I would only use the ViewModel for the data that might actually be posted back to the server. For all the other data, like lists, I would put it on the ViewBag. Like:
public ViewResult SomeAction()
{
var model = GetYourModelData();
ViewBag.TList = GetTList();
ViewBag.GList = GetGList();
ViewBag.SList = SList();
return View(model);
}
You could put all the lists in a separate helper object if you use them a lot.
Note that this is not a "this is how you should do it answer", it is more a description of what works for me. But as I see it the model of the view is one thing and the actual data, as data in drop downs etc., on the view is another thing and should be put in the ViewData property, but the ViewBag is just a dynamic wrapper around the ViewData property. You can then use the properties on the ViewBag as input to your partial views that should make up each of your sections.

Resources