Ajax.ActionLink does not call controller action and its view - ajax

Here, the actionlink 'Get Students' in TeacherIndex view of TeacherController must call StudentController and action method StudentList and then go to the view StudentIndex.
TeacherIndex.cshtml in TeacherController:
#model IEnumerable<StudentMVC.Models.TeacherEntity>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.TeacherId)
</th>
...
</tr>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.TeacherId)
</td>
...
<td>
#Ajax.ActionLink("Get Students", "StudentList", "Student", new { id = item.TeacherId }, new AjaxOptions { HttpMethod = "POST" })
</td>
</tr>
}
}
StudentController:
[HttpPost]
public ActionResult StudentList(int TeacherId)
{
List<StudentEntity> studentList = new List<StudentEntity>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Moviedb"].ConnectionString);
SqlCommand cmd = new SqlCommand("SP_Student", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TeacherId", TeacherId);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
StudentEntity student = new StudentEntity();
student.StudentId = Convert.ToInt32(dr["StudentId"]);
//...
studentList.Add(student);
}
con.Close();
return View("StudentIndex", studentList);
}
But here, instead of that, shows
Server Error in '/' Application. The resource cannot be found.
Requested URL: /Student/StudentList/1

the name of parameter should be same. use this :
#Ajax.ActionLink("Get Students", "StudentList", "Student", new { #TeacherId = item.TeacherId }, new AjaxOptions { HttpMethod = "POST" })

Related

.Net MVC 4. Ajax

I want to search result from db andy show on same view using ajax but it is not happening. Here is my Index page where I defined the Search box and a table to show search result.
Index View is
#{
Layout = null;
}
#model IEnumerable<BR.Models.PostJob>
#using (Ajax.BeginForm("AjaxSearch", "Student",
new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchResults" }))
{
<input type="text" name="q" />
<input type="submit" value="Search" />
}
My Table to show Searched result is.
<table id="searchResults">
</table>
My Controller Function is.
public PartialViewResult AjaxSearch(string q)
{
SqlDataReader dr;
SqlConnection con = new SqlConnection("Data Source=IT-INTERN3;Initial Catalog=bridging_the_gap;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "select * from Jobs where job_title ='" + q + "'";
cmd.Connection = con;
var r = cmd.ExecuteReader();
return this.PartialView(r);
}
My Partial View is
#model IEnumerable<BR.Models.PostJob>
<table>
<tr>
<th>
id
</th>
<th>
job_title
</th>
<th>
job_description
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#item.id
</td>
<td>
#item.job_title
</td>
<td>
item.job_description
</td>
</tr>
}
</table>
On click of search button it is going to AjaxSearch function but not showing result in Index view.
You must map ExecuteReader result to object(PostJob).
In AjaxSearch action replace this line
var r = cmd.ExecuteReader();
with
List<PostJob> results = new List<PostJob>();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.Read())
{
PostJob newItem = new PostJob();
newItem.id = dr.GetInt32(0); // 0 is id column order
newItem.job_title = dr.GetString(1); // 1 is job_title column order
newItem.job_description = dr.GetString(2);
results.Add(newItem);
}
}
return PartialView(results);

How can I prevent a partial view from disappearing upon submit?

I’m using BeginForm inside of a child view. When I submit the form I’m still on the parent view but the child view goes away. I would like for the information to be submitted but the form to remain until the user wants to load another partial view or move away from the page entirely. Is there a way to prevent the page from disappearing upon submit? Here’s what my BeginForm looks like:
using (Html.BeginForm("Action", "Controller", new { fromTeacherPage = true, searchTeacher = instructorName, selectedDepartment = Model.Assignments.FirstOrDefault().departmentNumber, id = Model.Assignments.FirstOrDefault().InstructorId, strCategoryName = #ViewBag.categoryname }, FormMethod.Post, new { #name = "formName", #class = "nameOfClass" }))
{
//code for form here
<button id="submitButton" class="submitButton">Submit</button><br />
}
UPDATE:
<script type="text/javascript">
$(document).ready(function () {
$("#datep").datepicker({ showOn: "both", buttonText: "Select Date", changeMonth: true, changeYear: true, yearRange: "-2:+2", showOtherMonths: true, onSelect: function (date, datepickder) {
var sltdDate = { selectedDate: date };
$.ajax({
type: "GET",
url: "/Schedule/GetSchedule",
data: sltdDate,
datatype: "html",
success: function (data) {
$("#returnedData").html(data);
$("#returnedData #dateContainer").remove();
$("<button>Hide</button>").appendTo("#homeworkUpdateId-0")
}
});
}
});
});
</script>
#{
int? intTeacherID = Convert.ToInt32(HttpContext.Current.Session["intTeacherId"]);
string instructorName = (from x in Model.Enrollments where x.InstructorId == intTeacherID select x.InstructorFullName).FirstOrDefault();
}
<div id="dateContainer">
<label for ="datep">Date: </label><input id="datep" />
</div>
<div id="returnedData">
#if (Model.Assignments != null)
{
using (Html.BeginForm("Action", "Controller", new { fromTeacherPage = true, searchTeacher = instructorName, selectedDepartment = Model.Assignments.FirstOrDefault().departmentNumber, id = Model.Assignments.FirstOrDefault().teacherId, strCategoryName = #ViewBag.categoryname }, FormMethod.Post, new { #name = "formName", #class = "submitAttendance" }))
{
<table>
<tr>
<th>
Grade
</th>
<th>
Attendance
</th>
<th>
Clas Day
</th>
<th>
Assignment Type
</th>
<th>
Overall Grade
</th>
</tr>
#foreach (var assignment in Model.Assignments.Select((x, i) => new { Data = x, Index = i }))
{
int asgnIndex = assignment.Index;
<tr id="rowId+#asgnIndex">
<td>
<div id="homeworkUpdateId-#asgnIndex">
#Html.TextBox("HomeworkGrade", assignment.Data.HomeworkGrade.ToString(), new { style = "width:55px; text-align: center" })
</div>
</td>
</table>
<button id="submitButton" class="submitButton">Submit </button><br />
}
}
</div>
You are using
using(Html.BeginForm()){}
this will refresh the whole page if you only want to reload some section inside your view you have to use
using (Ajax.BeginForm("Action", "Controller", null, new AjaxOptions {UpdateTargetId = "divToUpdate", InsertionMode = InsertionMode.Replace, HttpMethod = "GET"}, new {id = "someIdFOrm"}))

how to dynamically edit the bind data in sql using mvc3 web grid

i am new to mvc.. i have a task that, i have to bind data from existing table in sql using asp.net mvc3(Razor) Web Grid .. now i have to edit the data in webGrid.. i dont know how the edit operation is going to made... Plzz Help me out...
i have given my bind data.. plz let me know how to edit it...
Controller:
public ActionResult Index()
{
var list = GetList();
return View(list);
}
public List<Teacher> GetList()
{
var modelList = new List<Teacher>();
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Demo;Data Source=CIPL41\SQLEXPRESS"))
{
conn.Open();
SqlCommand dCmd = new SqlCommand("Select T_Id,T_Name,T_Address,Sub_Id from teacher", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new Teacher();
model.T_Id = Convert.ToInt32(ds.Tables[0].Rows[i]["T_Id"]);
model.T_Name = ds.Tables[0].Rows[i]["T_Name"].ToString();
model.T_Address = ds.Tables[0].Rows[i]["T_Address"].ToString();
model.Sub_Id = ds.Tables[0].Rows[i]["Sub_Id"].ToString();
modelList.Add(model);
}
}
return modelList;
}
//
Index.cshtml
#model IEnumerable<MvcApplication1.Models.Teacher>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Index", "Teacher"))
{
<table>
<tr>
<th></th>
<th>
T_Id
</th>
<th>
T_Name
</th>
<th>
T_Address
</th>
<th>
Sub_Id
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.T_Id }) |
#* #Html.ActionLink("Details", "Details", new { id=item.T_Id }) |*#
#Html.ActionLink("Delete", "Delete", new { id=item.T_Id })
</td>
<td>
#Html.TextBox("T_Id", item.T_Id , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Name", item.T_Name , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("T_Address", item.T_Address , new { #style = "width:100px;" })
</td>
<td>
#Html.TextBox("Sub_Id",item.Sub_Id,new { #style = "width:100px;"})
</td>
</tr>
}
</table>
Plz help me out....
Have a look at this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view
I think it explains exactly what you're trying to do.

why ajax.actionlink not refresh the page?

First,sorry to my bad english.
I don't understand why my page not refresh when i click on the delete user...
After the click i check in database and the user is delete but my page with table not refresh, i dont't understand.
My views is:
#model IEnumerable<SiteWebEmpty.Models.User.UserDisplay>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.debug.js")" type="text/javascript"></script>
<h2>Display User</h2>
<div id="deleteUser">
#using (Html.BeginForm())
{
<table class="tabledisplayUser" border="1">
<tr>
<th>Name FirstName</th>
<th>UserName</th>
<th>Roles</th>
<th>Choice</th>
</tr>
<tr>
<th>#Html.Editor("name")</th>
<th>#Html.Editor("username")</th>
<th>#Html.Editor("roles")</th>
<th>#Html.Editor("choice")</th>
</tr>
#foreach (var user in Model)
{
<tr>
<td class="action nameFirstName">#Html.DisplayFor(u => user.NameFirstName)</td>
<td class="action userName">#Html.DisplayFor(u => user.UserName)</td>
#if (user.Roles.Roles.Count.Equals(0))
{
<td>Nobody Role</td>
}
else
{
<td>#Html.DropDownList("Roles", user.Roles.Roles)</td>
}
<td>#Html.ActionLink("Edit", "Edit", new { UserName = user.UserName }) | #Ajax.ActionLink("Delete", "Delete", new { UserName = user.UserName },
new AjaxOptions()
{
HttpMethod = "POST",
Confirm = "Do you want delete this user?",
UpdateTargetId = "deleteUser"
})</td>
</tr>
}
</table>
}
</div>
My controller is:
public ActionResult DisplayUser()
{
List<UserDisplay> users=getAllUserInDB();
GetAllNameFirstNameLDAP(users);
return View(users);
}
public ActionResult Delete(String userName)
{
DeleteDB(userName);
if (!Request.IsAjaxRequest())
return RedirectToAction("DisplayUser");
else
{
List<UserDisplay> users = getAllUserInDB();
GetAllNameFirstNameLDAP(users);
return PartialView("DisplayUser",users);
}
}
I don't understand why it not working, thank you for your help !
UpdateTargetId = "deleteUser" means to refresh a DOM element with id="deleteUser". You don't have such element.
You have:
<div class="deleteUser">
which is not the same as:
<div id="deleteUser">
So replace the class with id and your table should refresh normally.

MVC3 Ajax.BeginForm with javascript disabled

I'm having a problem getting a form to work without javascript being enabled.
This should be enough to go on, ask if you need to know anything else - I don't want to just put the whole solution up here!
~/Views/_ViewStart.cshtml:
#{ Layout = "~/Views/Shared/Layout.cshtml"; }
~/Views/Shared/Layout.cshtml:
#using System.Globalization; #{ CultureInfo culture = CultureInfo.GetCultureInfo(UICulture); }<!DOCTYPE html>
<html lang="#culture.Name" dir="#(culture.TextInfo.IsRightToLeft ? "rtl" : "ltr")">
<head>
<title>AppName :: #ViewBag.Title</title>
<link href="#Url.Content("~/favicon.ico")" rel="shortcut icon" type="image/x-icon" />
<link href="#Url.Content("~/apple-touch-icon.png")" rel="apple-touch-icon" />
<link href="#Url.Content("~/Content/css/site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Content/js/jquery-1.6.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/js/app.js")" type="text/javascript"></script>
#RenderSection("SectionHead", false)
</head>
<body>
<div id="page-container">
<div id="nav">
<div id="nav-user">
#{ Html.RenderAction("LoginStatus", "Account"); }
#{ Html.RenderPartial("CultureSelector"); }
</div>
</div>
<div id="page-content">
<h2>#ViewBag.Title</h2>
#RenderBody()
</div>
</div>
</body>
</html>
~/Views/Account/Index.cshtml:
#model AccountFilterModel
#{
ViewBag.Title = "Account Home";
var loadingId = "loading" + new Random().Next();
Model.FilterFormId = "filter-account-form";
}
#using (Ajax.BeginForm("List", "Account", Model, new AjaxOptions { UpdateTargetId = "result-list", LoadingElementId = loadingId }, new { id = "filter-account-form" })) {
<!-- form controls and validation summary stuff -->
<input id="filter" type="submit" value="Filter" />
<span id="#loadingId" style="display: none">
<img src="#Url.Content("~/Content/images/ajax-loader.gif")" alt="Loading..." />
</span>
}
<div id="result-list">
#{ Html.RenderAction("List", Model); }
</div>
~/Views/Account/List.cshtml:
#model FilterResultModel
#helper SortLink(AccountSort sort, SortDirection dir) {
string display = (dir == SortDirection.Ascending ? "a" : "d"); // TODO: css here
if (Model.Filter.SortBy != null && ((AccountSortModel)Model.Filter.SortBy).Sort == sort && dir == Model.Filter.SortOrder) {
#:#display
} else {
FilterModel fm = new FilterModel(Model.Filter);
fm.SortBy = AccountSortModel.SortOption[sort];
fm.SortOrder = dir;
#display
}
}
#if (Model.Results.Count > 0) {
var first = Model.Results.First();
<table>
<caption>
#string.Format(LocalText.FilterStats, Model.FirstResultIndex + 1, Model.LastResultIndex + 1, Model.CurrentPageIndex + 1, Model.LastPageIndex + 1, Model.FilteredCount, Model.TotalCount)
</caption>
<thead>
<tr>
<th>
#Html.LabelFor(m => first.Username)
<span class="sort-ascending">
#SortLink(AccountSort.UsernameLower, SortDirection.Ascending)
</span>
<span class="sort-descending">
#SortLink(AccountSort.UsernameLower, SortDirection.Descending)
</span>
</th>
<!-- other table headers -->
</tr>
</thead>
<tbody>
#foreach (AccountModel account in Model.Results) {
<tr>
<td>#Html.EncodedReplace(account.Username, Model.Filter.Search, "<span class=\"filter-match\">{0}</span>")</td>
<!-- other columns -->
</tr>
}
</tbody>
</table>
Html.RenderPartial("ListPager", Model);
} else {
<p>No Results</p>
}
Relevant part of AccountController.cs:
public ActionResult Index(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return View(fm);
}
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
With javascript enabled, this works fine - the content of div#result-list is updated as expected.
If I don't do the Request.AjaxRequest() and just return the PartialView, then with javascript disabled I get a page with just the content of the results on it. If I have the code as above, then I get a StackOverflowException.
How do I get this to work?
Solution
Thanks to #xixonia, I discovered the problem - here is my solution:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue)
fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
if (Request.HttpMethod == "GET")
return PartialView("List", Service.Get(fm));
if (Request.HttpMethod == "POST")
return Request.IsAjaxRequest() ? (ActionResult) PartialView("List", Service.Get(fm)) : RedirectToAction("Index", model);
return new HttpStatusCodeResult((int) HttpStatusCode.MethodNotAllowed);
}
You can use the following extension method to determine if the request is an ajax request
Request.IsAjaxRequest()
If it is, you can return a partial view, otherwise you can return a full view or redirect.
if(Request.IsAjaxRequest())
{
return PartialView("view", model);
}
else
{
return View(model);
}
edit: here's the problem:
The "List" is returning the "Index" view when the request is not an AJAX request:
public ActionResult List(AccountSort? accountSort, FilterModel model = null) {
FilterModel fm = model ?? new FilterModel();
if (accountSort.HasValue) fm.SortBy = AccountSortModel.SortOption[accountSort.Value];
return Request.IsAjaxRequest() ? (ActionResult)PartialView("List", Service.Get(fm)) : View("Index", model);
}
The "Index" view is rendering the "List" action:
#{ Html.RenderAction("List", Model); }
AKA: Recursion.
You need to engineer a way to display your list without drawing the index page, or make your index page draw a partial view with your list modal as a parameter.

Resources