Under-hood explanation required for asp.net MVC tutorial - asp.net-mvc-3

refer to asp.net MVC tutorial:
http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view
regarding the autogenerated Views\Movies\SearchIndex.cshtml
Question 1:
<p>
#Html.ActionLink("Create New", "Create")
#using (Html.BeginForm())
{
<p>
Genre: #Html.DropDownList("movieGenre", "All")
Title: #Html.TextBox("SearchString", "Movies", FormMethod.Get)
<input type="submit" value="Filter" />
</p>
}
</p>
how does movieGenre refer to #ViewBag.movieGenre, which is obviously defined in Controllers/MoviesController.cs
Question 2:
#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>
<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>
}
where is modelItem defined? VS2010 shows me modelItem is
IEnumerable <MvcMovie.Model.Movie>
Thanks.

Looks like you've already answered your second question, so I'll just answer your first:
The Html.DropDownList helper will bind itself to ViewData by default if no data is provided to it. ViewBag is simply a dynamic wrapper around the ViewData dictionary, so when you set ViewBag.movieGenre = new SelectList() you are effectively setting ViewData["movieGenre"] = new SelectList().
Now that you have this SelectList in your ViewData, the following will automatically bind this to the dropdown:
#Html.DropDownList("movieGenre")
This implicit binding isn't very well documented. See here for more information:
http://weblogs.asp.net/pjohnson/archive/2012/10/26/mvc-s-html-dropdownlist-and-quot-there-is-no-viewdata-item-of-type-ienumerable-lt-selectlistitem-gt-that-has-the-key.aspx

Related

PartialView is not working (whole page refresh instead)

Hello I am new to MVC 4. I am having a problem with partialView.. I goole it and searched alot and studied different tutorials but couldn't find any solution that can address my problem.I created a PagedList to display records at Index.cshtml page. Then I created PartialIndex.cshtml page to display records in Partial View.
Here is problem: When I click on any page number or navigate.. whole page refreshes and post back... partial view is not working.Don't Know where I am doing wrong.
I want to show table inside the DIV in PartialIndex.cshtml
PartialIndex.cshtml:
<div id="targetContainer"> //I want to show this DIV in partial view.
<table>
<tr>
<th>
#Html.ActionLink("ID", "Index", new { sortOrder = ViewBag.customerID, currentFilter=ViewBag.CurrentFilter })
</th>
<th>
</th>
<th>
#Html.DisplayName("First Name")
</th>
<th></th>
<th>
#Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.lName, currentFilter=ViewBag.CurrentFilter })
</th>
<th></th>
<th>
#Html.DisplayName("Contact Num")
</th>
<th>
#Html.DisplayName("Address")
</th>
<th>
#Html.DisplayName("Email")
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.customerId)
</td>
<td>
</td>
<td>
#Html.DisplayFor(modelItem => item.fName)
</td>
<td>
</td>
<td>
#Html.DisplayFor(modelItem => item.lName)
</td>
<td>
</td>
<td>
#Html.DisplayFor(modelItem => item.contactNum)
</td>
<td>
</td>
<td>
#Html.DisplayFor(modelItem => item.address)
</td>
<td>
</td>
<td>
#Html.DisplayFor(modelItem => item.email)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID })
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
</div>
<br />
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(
new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "GET", UpdateTargetId = "targetContainer" }))
Index.cshtml:
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("PartialIndex")
You should better use
Html.RenderPartial("~/Views/Shared/_Yourpartial.cshtml")
Html.RenderPartial("~/Views/Shared/PartialIndex.cshtml")

Post multiple data from an loaded form ajax mvc 4

I have a form like this
<table>
<thead>
<tr>
<th>Tên học sinh </th>
<th>Giáo lý viên </th>
<th>Năm Học</th>
<th>Điểm TB Học Kỳ 1 </th>
<th>Điểm TB Học Kỳ 2 </th>
<th>Điểm Tổng Kết Năm Học </th>
<th>Lớp </th>
</tr>
</thead>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<tbody id="addDetails">
<tr>
<td>
#Html.DropDownList("HocSinhId", String.Empty)
#Html.ValidationMessageFor(model => model.HocSinhId, null, new { #class = "help-inline" })
</td>
<td>
#Html.DropDownList("GiaoLyVienId", String.Empty)
#Html.ValidationMessageFor(model => model.GiaoLyVienId, null, new { #class = "help-inline" })
</td>
<td>
#Html.TextBoxFor(model => model.NamHoc)
#Html.ValidationMessageFor(model => model.NamHoc, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTBHK1)
#Html.ValidationMessageFor(model => model.DiemTBHK1, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTBHK2)
#Html.ValidationMessageFor(model => model.DiemTBHK2, null, new { #class = "help-inline" })
</td>
<td>
#Html.EditorFor(model => model.DiemTongKetNamHoc)
#Html.ValidationMessageFor(model => model.DiemTongKetNamHoc, null, new { #class = "help-inline" })
</td>
<td>
#Html.DropDownList("LopId", String.Empty)
#Html.ValidationMessageFor(model => model.LopId, null, new { #class = "help-inline" })
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
#Ajax.ActionLink("Add", "AddDetails", new AjaxOptions
{
HttpMethod = "GET",
OnSuccess = "successCall",
#*UpdateTargetId = "addDetails",
InsertionMode = InsertionMode.InsertAfter,*#
})
</td>
</tr>
<tr>
<td colspan="6">
#* *#
<input type="submit" value="Lưu thông tin" class="button" />
</td>
</tr>
</tfoot>
</fieldset>
}
</table>
After click Ajax link "Add" it will insert new row to input new data.
Image: http://i808.photobucket.com/albums/zz1/nquangkhaiDST/Postmultipledata_zps5364f0a0.png
The Question is: When I submit to server, it just post the first data, not the data after i click "Add". How i can get all the data even field from ajax to post back to server.
Anyone know how to post all the data even the data of ajax. Thanks a lots
Assuming you'll be adding that same type of object when you click Add, what you need to do is accept an array of your model object in your Post controller parameter.
[HttpPost]
public ActionResult(MyObject[] objects)
{
// do something
}
did you check your html on client side.... while submitting from client side you have to make sure that that the controls added on the page must have naming convention like
<input type="text" value="" name="IncomeDetails[0].IncomeCode" id="IncomeDetails_0__IncomeCode" class="incomeCode valid" disabled="disabled">
on the first row and
<input type="text" disabled="disabled" class="incomeCode valid" id="IncomeDetails_1__IncomeCode" name="IncomeDetails[1].IncomeCode" value="">
on the second row then only while submitting you can get full list of objects.

Partial view renders as full view

MVC 3 , ajax, c#
My partial view is rendering as a new page instead of replacing the search results table.
Controller:
public class SearchController : Controller
{
//
// GET: /Search/
private myEntities db = new myEntities();
private Repository repo = new Repository();
[HttpGet]
public ActionResult Index()
{
var model = new List<PersonViewModel>();
model = repo.GetPeople();
return View(model);
}
public PartialViewResult _SearchResult(string fname, string lname)
{
var personResult = repo.GetSearchResult(fname, lname);
return PartialView("_SearchResult", personResult);
}
}
The view:
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
<table id="indexSearchResults" class="data-table">
<tr>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Gender
</th>
<th>
City
</th>
<th>
DOB
</th>
<th>
IsStudent
</th>
<th>
Actions
</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan=7>
There are currently no trespassers in the trespass database.
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.School)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PersonId }) |
#Html.ActionLink("Details", "Details", new { id = item.PersonId }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PersonId })
</td>
</tr>
}
}
</table>
</div>
</div>
And the partial view:
#model IEnumerable<TrespassTracker.Models.PersonViewModel>
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Gender
</th>
<th>
Date of Birth
</th>
<th>
Is a Student?
</th>
<th>
Actions
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsStudent)
</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>
}
</table>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
From my research I found the usual suspect to be the missing link to the jquery script in the partial, but I had that. I checked the network tab on my wed dev tools and found it is being called. What else could the problem be?
the script won't cause any problem and the only thing I see wrong here is the table. you are trying yo fill the table with other table which returns a table, use a div instead to update the ajax form (search result):
<div id="indexSearchResults">
<table>
..........
</table>
</div>
Try this
<div class="page">
<div class="middle-col-comment-mod">
<h2>Search Existing Trespassers</h2>
<div id="search">
#using (Ajax.BeginForm("_SearchResult", "Search", null, new AjaxOptions { HttpMethod = "Post", InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace, UpdateTargetId = "indexSearchResults" }))
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBox("FirstName")
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBox("LastName", "", new { style = "margin-right: 15px;" })
<input type="submit" name="submit" class="skbutton" value="Search" />
</div>
}
</div>
#if (Model.Count() == 0)
{
<label>There are currently no trespassers in the trespass database. </label>
}
else
{
foreach (var item in Model)
{
#Html.Partial("__SearchResult",item)
}
</div>
</div>
How 'bout to use jQuery do reload your result content, instead Post from your form? You can named some div with an ID and uses it as reference do jQuery.load() (considering you're using that ViewModel you passed into Index action):
1.View
#model YourModel
<!-- ... -->
<div id="search">
#using (Ajax.BeginForm("MainPostAction", "ControllerName", FormMethod.Post, new { id = "yourFormID" })
{
<div class="editor-field">
<label>First Name:</label>
#Html.TextBoxFor(model => model.FirstName)
<label style = "margin-left: 15px;">Last Name:</label>
#Html.TextBoxFor(model => model.LastName, new { style = "margin-right: 15px;" })
<input type="button" name="submit" id="searchButton" class="skbutton" value="Search" />
</div>
<div id="results"></div>
}
</div>
Javascript:
$(document).ready(function() {
$('#searchButton').click(function(event) {
$('#results').load('#Url.Action('_SearchResult', 'Search')', $('#yourFormID').serialize());
});
}
Your action remains the same.
How 'bout it?

How can i remove a deleted row inside a table using Jquery for my asp.net MVC

i have the following view:-
<script type="text/javascript">
$(document).ready(function () {
$("#removerow").click(function () {
$(this).remove();
});
});
</script>
<h2>Details</h2>
<fieldset>
<legend>This Question Currently has #Model.Answers.Count() Answers/s. </legend>
<table id="incrementanswer">
<tr>
<th>
Description
</th>
<th>
Answer
</th>
<th></th>
</tr>
#foreach (var answer in Model.Answers.OrderBy(a=> a.IsRight))
{
<tr id = "removerow">
<td>
#Html.DisplayFor(modelItem => answer.Description)
</td>
<td>
#Html.DisplayFor(modelItem => answer.Answer_Description.description)
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = answer.AnswersID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete this Answer ?",
HttpMethod = "Post",
UpdateTargetId = "toremove",
OnSuccess = "removePartial2"
})
</td>
</tr>
}
</table>
<div id = "progress2">
<img src= "#Url.Content("~/Content/images/ajax-loader1.gif") ">
</div>
which contains a script and an ajax.actionlink that calls this script after clicking on the delete link. Currently the row will be removed only if it is the first row in a table and also the row will be deleted before confirming the deletion ,, so what might be the problem ?
edited:- i have updated my view to the following, but i still can not force the removePartial2 script to remove the row which was deleted:-
</script>
<script type="text/javascript">
function removePartial2() {
$(this).remove();
}
</script>
}
<h2>Details</h2>
<fieldset>
<legend>This Question Currently has #Model.Answers.Count() Answers/s. </legend>
<table id="incrementanswer">
<tr>
<th>
Description
</th>
<th>
Answer
</th>
<th></th>
</tr>
#foreach (var answer in Model.Answers.OrderBy(a=> a.IsRight))
{
<tr id = #answer.AnswersID>
<td>
#Html.DisplayFor(modelItem => answer.Description)
</td>
<td>
#Html.DisplayFor(modelItem => answer.Answer_Description.description)
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = answer.AnswersID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete this Answer ?",
HttpMethod = "Post",
UpdateTargetId = #answer.AnswersID.ToString(),
OnSuccess = "removePartial2"
})
</td>
</tr>
}
</table>
<div id = "progress2">
<img src= "#Url.Content("~/Content/images/ajax-loader1.gif") ">
</div>
"Ids. Must. Be. Unique."
You have a function that removes the row if the ROW is clicked, not just the delete option. I would remove your first javascript block, and only use the ajax call function.
OnSuccess is whether or not the Ajax call returned a 200 code. This is only if the ajax call was successful - It's not checking to see if a returned value was correct.

Paging in a scaffolding view MVC3

so using EF4 I create a scaffolding controller/view, so my question is how can I Add Paging to my view in easy/fast way??
the
controller generated
public ViewResult Index()
{
return View(db.Perifericos.ToList());
}
the
view: generated
#model IEnumerable<Paginacion.Models.Perifericos>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Nombre
</th>
<th>
Modelo
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nombre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Modelo)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.idPerifericos }) |
#Html.ActionLink("Delete", "Delete", new { id=item.idPerifericos })
</td>
</tr>
}
</table>
Maybe this can help you: http://www.asp.net/entity-framework/tutorials/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
You have to implement a paging in controller and in the view add code like the link that i have given to you.
I use this one http://blogs.taiga.nl/martijn/2008/08/27/paging-with-aspnet-mvc/
It's support also ajax and areas
Easy to implement.
a complete msdn article with sample code
Sorting, Filtering, and Paging with the Entity Framework in an ASP.NET MVC Application

Resources