Regarding return view with model usage - asp.net-mvc

i am new in mvc. i have got a code where view is returning with model. what does it mean.
if i return view with model then model data can be access from view.
public ActionResult GetView(int id)
{
switch (id)
{
case 1:
return View("View1", model1);
break;
case 2:
return View("View2", model2);
break;
default:
return View("Default", modelDefault);
}
}
i need to see a small complete example where view will be return with model and view will be populated with model data. can anyone redirect me to a good example on this topic. thanks

Here you have a sample
CONTROLLER
public ActionResult Index()
{
// return a list of movies to view
return View(db.Movies.ToList());
}
VIEW
//declare expected type of model, if view returns something else, it will fail
#model IEnumerable<MvcMovie.Models.Movie>
//use model sent from controller
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<th>
#Html.DisplayFor(modelItem => item.Rating)
</th>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", { id=item.ID })
</td>
</tr>
}
More information on Accessing Your Model's Data from a Controller

Related

How to do a partial view on ActionLink

<table>
<tr>
<th>
Author
</th>
<th>
Title
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
#Ajax.ActionLink("View Reviews", "View", new { id = item.ID }, new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.InsertAfter })
</td>
</tr>
}
</table>
<div id="result">
</div>
public PartialViewResult View(int id)
{
ReviewModel reviewModel = new ReviewModel();
return PartialView(reviewModel.GetReviews(id));
}
Once the response has been sent to the client, the server is done. That means you can't directly have a partial view rendered based on a click, because those are two disjointed processes: a partial view is rendered server-side, while a click is registered client-side, once the server is already out of the picture.
Anytime you're talking about changing the already rendered page in client with some new information from the server, you're talking about AJAX, so you will need to handle that with JavaScript on the client-side, that catches the click event and requests the partial view from the server. That means you'll also need an action, server-side that your JavaScript can send a request to and that returns your partial view.
ReviewsController
public ActionResult View(int id)
{
// fetch reviews for `id`
if (Request.IsAjaxRequest())
{
// return partial for AJAX requests
return PartialView("_ReviewsPartial", reviews);
}
else
{
// return full view for regular requests
return View(reviews);
}
}
Main View
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
#Html.ActionLink("View Reviews", "View", new { id=item.ID }, new { #class = "GetReviewsLink", data_id = item.ID })
</td>
</tr>
}
<div id="SomeDiv"></div>
JavaScript
$(document).ready(function () {
$('.GetReviewsLink').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
$.get('#Url.Action("View")', { id: id }, function (result) {
$('#SomeDiv').html(result);
});
});
});
That will dump the rendered partial from the server into the div with id, "SomeDiv". You can then display it however you want. For example, you may have a static region that will just switch out the reviews as each item's link is clicked. "SomeDiv" may actually be the inner part of a modal window, that you could then show after the new content has been loaded in. However you want to handle the display.

How to highlight a new added entry in MVC?

I've created a DB application in MVC 4 using EntityFramework. It works okay, however I couldn't find the way of highlighting new added item to my table(html). Is it possible to highlight new rows in DB applications in MVC? Like in C#:
DataGrid.SelectedItem
Any advice or help would be very clarifying. How to highlight a row in MVC?
How are you rendering the table?
One option is to use TempData. Store the identifier of the added item in TempData and check for the identifier when rendering the table.
ItemController:
// POST: /Item/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="Id,Name")] Item item)
{
if (ModelState.IsValid)
{
db.Items.Add(item);
db.SaveChanges();
TempData["AddedItemId"] = item.Id;
return RedirectToAction("Index");
}
return View(item);
}
Item view:
<!-- Views\Item\Index.cshtml -->
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
var className = "";
if (TempData["AddedItemId"] != null && (int)TempData["AddedItemId"] == item.Id)
{
className = "alert-info";
}
<tr class="#className">
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>

MVC NullReferenceException

When I am sending information to the Database in MVC and I am redirecting the page and calling the view which prints out the newly stored data, I get a NullReferenceException error:
"Object reference not set to an instance of an object."
Apparently, my Model is null:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.CustomerID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
This is my Controller:
public ActionResult Index()
{
var customer = db.Customer.ToList();
return View();
}
Which gets called by:
[HttpPost]
public ActionResult Create(CustomerModel customer)
{
db.Customer.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
I don't understand why it's null....
public ActionResult Index()
{
var customer = db.Customer.ToList();
return View(customer);
}
You are never passing the customer object to the view.
Edit: Also not wrapping your db.SaveChanges(); in a try/catch can be dangerous when an exception occurs.

MVC 3 model item passed into dictionary error

I get this error and i don't understand why:
The model item passed into the dictionary is of type 'Devart.Data.Linq.DataQuery`1[CHRContext.WIKIIDEE]', but this dictionary requires a model item of type 'CHRContext.WIKIREPARTO'.
method from model
public IQueryable<WIKIIDEE> GetIdeasByDeptID(int id)
{
var query = from i in db.WIKIIDEEs
where i.IDREPARTO == id
select i;
return query;
}
method from controller
public ActionResult List(int id)
{
try
{
IdeeRepository ideeRepo = new IdeeRepository();
IQueryable<WIKIIDEE> list = ideeRepo.GetIdeasByDeptID(id);
return View(list);
}
catch (Exception Ex)
{
return View("Error");
}
}
and view
#model IEnumerable<CHRContext.WIKIIDEE>
#{
ViewBag.Title = "List";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>List</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
IDREPARTO
</th>
<th>
DATAINSERIMENTO
</th>
<th>
DESCRIZIONE
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.IDREPARTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DATAINSERIMENTO)
</td>
<td>
#Html.DisplayFor(modelItem => item.DESCRIZIONE)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
I ran into a very similar issue and was able to work around it. You can see how, here in my answer: The model item passed into the dictionary is of type A, but this dictionary requires a model item of type B

asp.net mvc viewdata to display category name

I am using ado.net entity model from an existing database.
I am using two tables products and categories.
I have a product controller:
public ActionResult Products()
{
using (var db = new StoreMvcEntities())
{
ViewData["categories"] = db.Categories.ToList();
return View(db.Products.ToList());
}
}
and a view:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.category.categoryname)
</td>
<td>
#Html.DisplayFor(modelItem => item.price)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
Here is the problem: in the controller, if I remove the ViewData["categories"] = db.Categories.ToList(); the product category name is empty in the view. I'm not using the ViewData["categories"] in the view, and to get to product category name, I have to invoke
db.Categories and affect the result to any viewdata.
Can anybody explain to me how this is working?
My guess is that you're running into a side effect of Model Binding. Does the Products class have a property for the Category class?

Resources