I want to write some sql queries(insert/update) in mvc3 .cshtm file and perform operations accordingly.I am new to this so I need help. Thank you in advance
-
1Queries should be made in the controller, the result of the query can be passed with your model class or with dynamic ViewBag to your cshtml view.Torben Schramme– Torben Schramme2013-09-10 10:43:57 +00:00Commented Sep 10, 2013 at 10:43
-
"Queries should be made in the controller" - That's a fine place to start (compared to putting queries into Views), but its usually better to abstract those queries to a Data Access Layer (usually a different Class Library project), and to have your ViewModel call the Data Access methods. The Controllers are ideally "thin", and do not know how your Data Access is actually conducted.GHP– GHP2013-09-10 12:06:16 +00:00Commented Sep 10, 2013 at 12:06
2 Answers
You can do:
@{
// You C# code here querying the database
}
BUT this is a very bad practice, such operations are the role of your Contoller.
In MVC your controller get and organize data and send data to the View. Then the role of the View is to only display data to the end-user.
If your data is complex you can (must) use a ViewModel (Views and ViewModels).
You can also use a ViewBag, ViewData, or TempData.
UPDATE:
using (var context = new BloggingContext())
{
var blogs = context.Blogs.ToList();
foreach (var item in blogs)
{
// Display blog for example
}
}
If you are using EntityFramework you can find more details on their Home page
The cshtml file is a view file in ASP.NET MVC. Accordingly, you would not put data access code within a view as it would be a violation of the design pattern; Views should be dumb and should be given the data they need to display a representation to the end user.
The controller should interact with the model to get data and pass it to the view. The general practice is to pass this data using a strongly typed ViewModel e.g.
public class MyController : Controller
{
public ActionResult Index()
{
// your data access code here
ViewModel model = someDataAccessCode.GetItemsForView();
return View(model);
}
}
and then a view called Index.cshtml in ~/Views/My/
@model ViewModel
@* Display data in the view model *@
If you really wanted to put data access code in the view then you can use server-side script blocks to do so. For Razor views, these are
@{
var data = someDataAccessCode.GetItemsForView();
}
@* Display data in the view model *@
But I wouldn't recommend this.