How to call drop down list by ajax call request when selected value changed? - asp.net

I work on web app mvc .NET framework I face issue i can't call function GetSelectedDropDownChanged when drop down selected changed .
I put break point to function GetSelectedDropDownChanged on controller WorkforceRequests
but it not hit or catched so what is issue
so what I try is :
<th>
<select class="form-control" id="statusselect" name="statusselectName">
<option value="1">Pending Request</option>
<option value="2">All requests </option>
</select>
</th>
when select from drop down I expect to call it ajax request call to function WorkforceRequests controller WorkforceRequests :
<script>
$(function () {
$(document)
.on('change', '#statusselect', function () {
var valueofDropDown = $(this).val();
var url = '/WorkforceRequests/GetSelectedDropDownChanged';
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
};
</script>
function i call from ajax request as below :
public class WorkforceRequestsController : Controller
{
[HttpGet]
public JsonResult GetSelectedDropDownChanged(string selectedValue)
{
List<WorkforceRequest> workforceRequest = new List<WorkforceRequest>();
if (selectedValue == "1")
{
workforceRequest = Workforce.GetPendingOnPalnningSection();
}
else
workforceRequest = Workforce.GetAllRequestsData();
return Json(new { myResult = workforceRequest }, JsonRequestBehavior.AllowGet);
}
}
data will returned as list from ajax call from function GetSelectedDropDownChanged ON table id dtbl
<table id="dtbl" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.WorkforceRequestID)
</th>
<th>
#Html.DisplayNameFor(model => model.DepartmentCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Section)
</th>
<th>
#Html.DisplayNameFor(model => model.RequiredPosition)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.WorkforceRequestID)
</td>
<td>
#Html.DisplayFor(modelItem => item.DepartmentCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Section)
</td>
<td>
#Html.DisplayFor(modelItem => item.RequiredPosition)
</td>
</tr>
}
</tbody>
</table>
Last Updated
I change my code inside view.cshtml to :
#model IEnumerable<HR.WorkforceRequisition.Models.WorkforceRequest>
#{
ViewBag.Title = "Pending Requests";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Pending Requests</h2>
<hr />
#if (!string.IsNullOrWhiteSpace(ViewBag.msg))
{
<div class="alert alert-success">
#ViewBag.msg
</div>
}
#if (!string.IsNullOrWhiteSpace(ViewBag.errorMsg))
{
<div class="alert alert-danger">
#ViewBag.errorMsg
</div>
}
#if (Session[BLL.Common.SessionKeys.RoleCode].ToString() == "REC" || Session[BLL.Common.SessionKeys.RoleCode].ToString() == "PLNG")
{
<th>
<select class="form-control" id="statusselect" >
#*<option>Select Status</option>*#
<option value="1">Pending Request</option>
<option value="2">All requests </option>
</select>
</th>
}
<table id="dtbl" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th></th>
<th>
#Html.DisplayNameFor(model => model.WorkforceRequestID)
</th>
<th>
#Html.DisplayNameFor(model => model.DepartmentCode)
</th>
<th>
#Html.DisplayNameFor(model => model.Section)
</th>
<th>
#Html.DisplayNameFor(model => model.RequiredPosition)
</th>
<th>
#Html.DisplayNameFor(model => model.JobTitle)
</th>
<th>
#Html.DisplayNameFor(model => model.ReportingTo)
</th>
<th>
#Html.DisplayNameFor(model => model.NationalityCategory)
</th>
<th>
#Html.DisplayNameFor(model => model.StatusRemark)
</th>
<th>
Requestor
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.ActionLink("Details", "Details", new { id = item.WorkforceRequestID })
</td>
<td>
#Html.DisplayFor(modelItem => item.WorkforceRequestID)
</td>
<td>
#Html.DisplayFor(modelItem => item.DepartmentCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Section)
</td>
<td>
#Html.DisplayFor(modelItem => item.RequiredPosition)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobTitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.ReportingTo)
</td>
<td>
#Html.DisplayFor(modelItem => item.NationalityCategory)
</td>
<td>
#Html.DisplayFor(modelItem => item.StatusRemark)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreatedByName)
</td>
</tr>
}
</tbody>
</table>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
#section scripts
{
<script>
$(document).ready(function () {
$("#statusselect").change(function () {
var valueofDropDown = $("#statusselect").val();
console.log(valueofDropDown);
var url = #Url.Action("GetSelectedDropDownChanged", "WorkforceRequests");
var dataToSend = { selectedValue: valueofDropDown }
$.ajax({
url: url,
data: dataToSend,
type: 'GET',
success: function (dataReceived) {
//update control on View
var receivedValue = dataReceived.myResult;
$('YourControlIDToUpdate').val(receivedValue);
}
})
});
}
</script>
}
Issue still not solved yet

#ahmed abdelaziz please check below code
you write a url before after get the value
var valueofDropDown = $(this).val();
var url = '/WorkforceRequests/GetSelectedDropDownChanged?selectedValue='+valueofDropDown;
have you check this one because I am not able to show in your code
#section scripts {
//stuff
}
_Layout.cshtml
#RenderSection("scripts", required: false)

Related

ASP.NET MVC Update fields of data Table at once

I have this view and I need to update the table Task upon the chosen values at Value Column View: EstimateValue. The view accepts #model IEnumerable then iterate the list of tasks and display them in Table.
The View
#model IEnumerable<Task>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table class="table table-striped table-hover table-bordered">
<thead>
<tr class="info">
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Value)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
#Html.HiddenFor(modelItem => item.ID)
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.EditorFor(modelItem => item.Value, new { #class = "form-control" })
#Html.ValidationMessageFor(modelItem => item.Value, "", new { #class = "text-danger" })
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
The Controller has the post method EstimateValue
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EstimateValue(IEnumerable<Task> TaskList)
{
if (ModelState.IsValid)
{
foreach (var task in TaskList)
{
db.Entry(task).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
//1. Rebound List to view
var TaskList = db.Tasks.ToList();
//2, return model to view
return View(TaskList);
}
When running the application the TaskList is null and I could not update the table Task. I have used JSON to send the data from the view as an array but still the values of TaskList are null
Change your IEnumerable to List because IEnumerable does not allow indexing. And instead of #foreach loop, use #for loop. So your View should be like this:
#model List<Task>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table class="table table-striped table-hover table-bordered">
<thead>
<tr class="info">
<th>
#Html.DisplayNameFor(model => Model[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => Model[0].Description)
</th>
<th>
#Html.DisplayNameFor(model => Model[0].Value)
</th>
</tr>
</thead>
<tbody>
#for(int i=0;i<Model.Count;i++)
{
<tr>
#Html.HiddenFor(modelItem => modelItem[i].ID)
<td>
#Html.DisplayFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].Description)
</td>
<td>
#Html.EditorFor(modelItem => modelItem[i].Value, new { #class = "form-control" })
#Html.ValidationMessageFor(modelItem => modelItem[i].Value, "", new { #class = "text-danger" })
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
Then change your Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EstimateValue(List<Task> TaskList)
{
if (ModelState.IsValid)
{
for(int i=0;i<TaskList.Count;i++)
{
db.Entry(TaskList[i]).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
//1. Rebound List to view
var TaskList = db.Tasks.ToList();
//2, return model to view
return View(TaskList);
}
If this solves your problem, accept the answer.

..NET MVC display partial view using ajax.ActionLink not working

I am using Ajax.ActionLink to send a request to my action method and update the SelectedSTRMList div with a partial view. However, the partial view is not displaying within the div when the link is clicked. I can view the partial view in a separate window. Any idea of what I am doing wrong?? In Chrome developer tools, I checked the ajax request in the Network tab and it is returning a request. I have also verified that I do have the ajax obstructive js files in ly layout view. Thanks
View
#model IEnumerable<NS.Models.FeeAuth>
<h2>Requests</h2>
<div class="table-responsive">
<table class="table table-condensed" style="border-collapse:collapse;">
<tr>
<th>
#Html.LabelFor(m => m.First().ID)
</th>
<th>
#Html.ActionLink("Request ID", "ApprovalIndex", new { sortOrder = ViewBag.RequestIDSortParam })
</th>
<th>
#Html.Label("emplid", "Student Emplid")
</th>
<th>
#Html.LabelFor(m => m.First().fname)
</th>
<th>
#Html.LabelFor(m => m.First().lname)
</th
<th></th>
</tr>
#{int i = 0;}
#foreach (var item in Model)
{
<tr data-toggle="collapse" data-parent="#collapse1_#i" data-target="#collapse1_#i" class="accordion-toggle">
<td>
#Ajax.ActionLink(Html.Encode(item.ID),
"SelectedSTRMS",
new
{
id = item.ID,
requestId = item.requestID
},
new AjaxOptions
{
UpdateTargetId = "SelectedSTRMList",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
})
</td>
<td>
#Html.DisplayFor(modelItem => item.requestID)
</td>
<td>
#Html.DisplayFor(modelItem => item.emplid)
</td>
<td>
#Html.DisplayFor(modelItem => item.fname)
</td>
<td>
#Html.DisplayFor(modelItem => item.lname)
</td>
</tr>
<tr>
<td colspan="6" class="hiddenRow">
<div class="accordian-body collapse" id="collapse1_#i">
<div id="SelectedSTRMList">
</div>
</div>
</td>
</tr>
i++;
}
</table>
</div>
_Layout View showing jquery
<script src="#Url.Content("~/Scripts/jquery-1.11.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.11.2.min.js")" type="text/javascript"></script>
#*<script src="#Url.Content("//ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.unobtrusive-ajax.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>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Partial View
<table>
<tr>
<td>
<ul>
#foreach (var s in (List<string>)ViewBag.SemesterInfo)
{
<li style="padding-bottom:20px;">#s</li>
}
</ul>
</td>
</tr>
</table>
Controller
public PartialViewResult SelectedSTRMS(int id, int requestId)
{
FeeAuthWithCommentsViewModel feeauth = new FeeAuthWithCommentsViewModel();
feeauth.FeeAuth = db.FeeAuths.Find(id);
int feeauthID = id;
List<string> GetSTRM = new List<string>();
GetSTRM = db.vw_GetSTRMs.Where(v => v.FeeAuthID == feeauthID).Select(v => v.DESCR).ToList();
if (GetSTRM.Count > 0)
{
ViewBag.SemesterInfo = GetSTRM.ToList();
}
else
{
ViewBag.SemesterInfo = new List<string> { "No STRM Selected" };
}
return PartialView("_SelectedSTRMS");
}

MVC Core 1.0 NullReferenceException: Object reference not set to an instance of an object

My code is trying to enumerate over a (currently empty) list of movies. When it gets to the ForEach loop it blows up with the stated error.
I would think it would just not iterate (moveNext()). How can I fix this behavior so that it will just display an empty list when the collection is blank
#using System.Collections.Generic
#using Microsoft.EntityFrameworkCore.Metadata.Internal
#using x.Models
#model IEnumerable<x.Models.Movie>
#{
ViewData["Title"] = "MovieView";
}
<h2>MovieView</h2>
<p>
<a asp-action="List">Movie List</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.Year)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (Movie item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.Year)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>

What do the `%%` (two percentage) characters mean in ASP.NET Razor MVC renderer?

What do these %% (two percentage characters) means in ASP.NET Razor MVC renderer?
#{
ViewBag.Title = %%Index%%;
}
When I create a new View, using the Add>View menu.
with These configuration:
i got the fallowing code:
#model IEnumerable<CadeMeuMedico.Models.Medico>
#{
ViewBag.Title = %%Index%%;
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.IDMedico)
</th>
<th>
#Html.DisplayNameFor(model => model.CRM)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.IDMedico)
</td>
<td>
#Html.DisplayFor(modelItem => item.CRM)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</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>

Html rendering order for asp mvc

How come my form loads like this?
Here is my code :
#using MvcApplication6.Models;
#model List<Employee>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
Create Entry
</p>
<p>#Html.ActionLink("Check departments", "Index", "Department")</p>
<p>Check summary</p>
<table border="1">
<tr>
<th>
#Html.DisplayNameFor(model => model[0].id)
</th>
<th>
#Html.LabelFor(model => model[0].firstname)
</th>
<th>
#Html.LabelFor(model => model[0].lastname)
</th>
<th>
#Html.DisplayNameFor(model => model[0].gender)
</th>
<th>
#Html.DisplayNameFor(model => model[0].department)
</th>
<th>Action</th>
</tr>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
foreach (Employee mod in Model)
{
<tr>
<td>
<input type="hidden" value="#mod.id" name="id" id="id" />
#Html.DisplayFor(modelItem => mod.id)
</td>
<td>
#Html.DisplayFor(modelItem => mod.firstname)
</td>
<td>
#Html.DisplayFor(modelItem => mod.lastname)
</td>
<td>
#Html.DisplayFor(modelItem => mod.gender)
</td>
<td>
#Html.DisplayFor(modelItem => mod.department)
</td>
<td>
<button onclick="location.href='#Url.Action("Edit", new { id = mod.id })';return false;">Edit</button>
#Html.CheckBoxFor(modelItem => mod.selected)
</td>
</tr>
}
<br />
<input type="submit" value="submit" />
}
</table>
Here are my concerns:
Notice that i put my submit button after the foreach loop but how come it was rendered first before the actual boxes?
I've been trying to put it on the bottom but i am having some problems.
What's the ordering for render?

Resources