Passing a Parameter to Javascript Function for ajax in mvc - javascript

I have a problem that I cannot handle. I have a ASP.NET MVC application. It's purpose is to listing items inside. These items are project activity with financial report of it. At the view, users suppose to view the financial information of the project activity and edit some values. Here is the view:
#model IEnumerable<DKMPPIB.Presentation.ViewModelKlasor.VarlikKlasoru.ProjectActivityFinancialReportViewModel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Region)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.ProjectName)
</th>
<th>
#Html.DisplayNameFor(model => model.FieldName)
</th>
<th>
#Html.DisplayNameFor(model => model.ProjectActivityName)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Region)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProjectName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FieldName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProjectActivityName)
</td>
<td>
<a onclick="readTender()" >
<img src='#Url.Content("~/Content/Images/glyphicons_free/glyphicons-342-briefcase.png")' />
</a>
</td>
<td>
<a href='#Url.Action("MyAction", "MyController")'>
<img src='#Url.Content("~/Content/Images/glyphicons_free/glyphicons-459-money.png")' />
</a>
</td>
#*Take attention to that line. I embed the ProjectActivityId here.*#
<td style="visibility:hidden" id="satirProjeFaaliyetId">#Html.DisplayFor(modelItem => item.ProjectActivityId)</td>
</tr>
}
</table>
<div id="tender-message" title="Tender Information" style="visibility:hidden">
<p>
<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
Here is your tender detail:
</p>
<p>
Currently using <b>36% of your budget </b>.
</p>
</div>
<script type="text/javascript">
function readTender(){
//I will make an ajax call to get tender information. I need ProjectActivityId for this.
alert("read tender");
//var projectActivityId = $('#ProjectActivityId').find(":selected").val();
//console.log(bolgeDropdownId);
//$.ajax({
// type: "POST",
// url: '/Erp/GetTenderInformation',
// data: "{ProjectActivityId :'" + projectActivityId + "'}",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: successFunc,
// error: errorFunc
//});
}
</script>
As mentioned above, the javascript function readTender needs projectActivityId as an input to read tender information. I write projectActivityId to the last td tag of view. How can I pass projectActivityId to readTender()?
Here is the content of ProjectActivityFinancialReportViewModel:
public class ProjectActivityFinancialReportViewModel
{
private ProjectActivityLocationViewModel _projectActivityLocationVM;
private ProjectActivityViewModel _projectActivityVM;
[Display(Name = "Region")]
public string Region
{
get
{
if (this._projeFaaliyetKonumVM == null)
return string.Empty;
else
return this._projectActivityLocationVM.RegionName;
}
}
[Display(Name = "City")]
public string City
{
get
{
if (this._projectActivityLocationVM == null)
return string.Empty;
else
return this._projectActivityLocationVM.CityName;
}
}
[Display(Name = "Field Name")]
public string FieldName
{
get
{
if (this._projectActivityLocationVM == null || this._projectActivityLocationVM.LocationVm != null)
return string.Empty;
else
return this._projectActivityLocationVM.LocationVm.Name;
}
}
[Display(Name = "Project Activity Name")]
public string ProjectActivityName
{
get
{
if (this._projectActivityVM == null)
return string.Empty;
else
return this._projectActivityVM.ActivityVM.Name;
}
}
[Display(Name = "Project Name")]
public string ProjectName
{
get
{
if (this._projectActivityVM == null)
return string.Empty;
else
return this._projectActivityVM.ProjectVM.Name;
}
}
public int ProjectActivityId
{
get
{
if (this._projectActivityVM == null || this._projectActivityVM.Id == null)
return int.MinValue;
else
{
int id = this._projectActivityVM.Id ?? int.MinValue;
return id;
}
}
}
public TenderViewModel TenderVM
{
get
{
if (this._projectActivityVM == null)
return null;
else
return this._projectActivityVM.TenderVM;
}
}
public ProjeFaaliyetMaliRaporveProjeFaaliyetViewModel()
{
this._projectActivityLocationVM = null;
this._projectActivityVM = null;
}
}

You can handle click event for each row.
I suppose "selection" is handled by "click" over the row.
You can do that in this way:
Change your javascript function:
function readTender(projectActivityId) {
...
}
Change your tr inside the foreach:
<tr onclick="javascript:readTender(#item.ProjectActivityId)">;
...
<tr>

<td style="visibility:hidden" id="satirProjeFaaliyetId">#Html.DisplayFor(modelItem => item.ProjectActivityId)</td>
Problem here is, that you try to find an element by an id that is not present:
$('#ProjectActivityId').find(":selected").val();
So change the top line to the following:
<td style="visibility:hidden;" id="ProjectActivityId">#item.ProjectActivityId</td>
and the line in your js-code to
$('#ProjectActivityId').val();

Related

How can i make the condition so that after read the card in text area, it updates the record that exists before it creates a new one?

https://prnt.sc/IsuRy9OhDic7 Screenshot To check what I am talking about.
Before it enters a new record it should save the TimeOut("HoraSaida") in the previous record.
I already did my research but I couldn't find anything that helps me out.
It reads the card in a text area with event change if it changes it saves the card number, it gets the date of record and the time in(hora entrada).
When it reads the second time it should save in the field time out (hora saida) before it enters a new record.
The Last field is a calculated field that gives the worked hours of that day.
Model
public partial class entradas_saidas
{
public int IdE_S { get; set; }
public Nullable<int> IdCartao { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DataRegisto { get; set; }
[DisplayFormat(DataFormatString = "{0:HH:mm:ss}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> HoraEntrada { get; set; }
[DisplayFormat(DataFormatString = "{0:HH:mm:ss}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> HoraSaida { get; set; }
public Nullable<int> HoraDiarias { get; set; }
}
Controller
[HttpPost]
public ActionResult AddReport(entradas_saidas es)
{
using (EMSistec bd = new EMSistec())
{
try
{
bd.entradas_saidas.Add(es);
bd.SaveChanges();
string message = "SUCCESS";
return Json(new { msg = message, JsonRequestBehavior.AllowGet });
}
catch (Exception)
{
String message = "ERROR";
return Json(new { msg = message, JsonRequestBehavior.AllowGet });
}
}
}
VIEW with Script
#using employeeManagement.Models;
#using PagedList.Mvc;
#model PagedList.IPagedList<employeeManagement.Models.entradas_saidas>
#*#model IEnumerable<employeeManagement.Models.entradas_saidas>*#
#{
ViewBag.Title = "EntradasSaidas";
}
<h2>EntradasSaidas</h2>
<h4 id="msg" style="color:red">#ViewBag.msg</h4>
#Html.Label("lblsearch", "Leitura do Cartão:", htmlAttributes: new { #class = "control-label col-md-2 " })
<textarea style="color:dodgerblue" id="readONchange"></textarea>
<br />
<p>
#Html.ActionLink("Create New", "AddEntradasSaidas")
</p>
<table class="table">
<tr>
<th>
#
#*#Html.DisplayNameFor(model => model.IdE_S)*#
</th>
<th>
#Html.ActionLink("Número Cartão", "EntradasSaidas", new { order = ViewBag.idcartao })
#*#Html.DisplayNameFor(model => model.IdCartao)*#
</th>
<th>
Data Registo
#*#Html.DisplayNameFor(model => model.DataRegisto)*#
</th>
<th>
Hora Entrada
#*#Html.DisplayNameFor(model => model.HoraEntrada)*#
</th>
<th>
Hora Saída
#*#Html.DisplayNameFor(model => model.HoraSaida)*#
</th>
<th>
Horas Diárias
#*#Html.DisplayNameFor(model => model.HoraDiarias)*#
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.IdE_S)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdCartao)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataRegisto)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraEntrada)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraSaida)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraDiarias)
</td>
<td>
#Html.ActionLink("Edit", "EditEntradasSaidas", new { id = item.IdE_S }) |
#*#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |*#
#*#Html.ActionLink("Delete", "DeleteMorada", new { id = item.IdMorada })*#
#Html.ActionLink("Delete", null, null, new { id = item.IdE_S, name = "dellink" })
</td>
</tr>
}
</table>
#((Model.PageNumber > Model.PageCount) ? 1:Model.PageNumber) de #Model.PageCount páginas.
#Html.PagedListPager(Model, (page) => Url.Action("EntradasSaidas", new { page, order = ViewBag.order }))
#*#section readcard{
<script>
function readCard() {
alert("HELLO");
}
</script>
}*#
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
es.IdCartao = $("#readONchange").val();
es.DataRegisto = param2;
if (es.IdCartao == "#readONchange" && es.HoraEntrada == null) {
es.HoraEntrada = param3;
} else {
es.HoraSaida = param3;
}
alert("AGORA AQUI")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Dado inserido com sucesso");
},
error: function () {
alert("ERRO! Nao foi possivel");
}
});
});
});
</script>
}
#section esDelete{
<script>
$(function () {
$("[name='dellink']").click((evt) => {
evt = evt ? evt : window.event;
evt.preventDefault();
if (!confirm("Tem a certeza que quer apagar o registo?")) return false;
$.ajax({
url: '#Url.Action("DeleteEntradasSaidas")',
dataType: 'json',
data: { id: evt.target.id },
success: function (data) {
console.log(JSON.stringify(data));
if (data.msg == "Registo apagado com sucesso!") $(evt.target).closest('tr').remove();
$("h4").html(data.msg);
},
error: function () { alert("Erro ao apagar registo!");}
});
});
});
</script>
}

Sort list of objects in MVC

I am trying to build page that shows all selected movies depending on genre,
with $.post
If genre is not selected page should show all movies.It is default selection.
This is Controller code:
public class BrowseController : Controller
{
private MovieContext context = new MovieContext();
// GET: Browse
public ActionResult Index()
{
ViewBag.Genres = context.Genre.ToList();
IEnumerable<Movie> mov = TempData["movies"] as IEnumerable<Movie>;
if (mov == null)
{
IEnumerable<Movie> movies = context.Movies.ToList();
return View(movies);
}
return View(mov);
}
[HttpPost]
public ActionResult Index(int id = -1)
{
IEnumerable<Movie> model;
if (id != -1)
{
model = context.Movies.Where(x => x.GenreId == id);
}
else
{
model = context.Movies.ToList();
}
ViewBag.Genres = context.Genre.ToList();
TempData["movies"] = model;
return RedirectToAction("", "Browse");
}
}
And this is the view code:
#model IEnumerable<Movies.Models.Movie>
#using Movies.Models
#{
ViewBag.Title = "Index";
var Movie = Model.FirstOrDefault();
List<Genre> Genres = ViewBag.Genres;
}
#Html.DropDownListFor(m => Movie.GenreId, new SelectList(Genres, "Id",
"Name"), "")
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Rating)
</th>
<th>
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Rating)
</td>
<td></td>
</tr>
}
</table>
#section Scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$('select#Movie_GenreId').on('change', function () {
var value = $(this).find(':selected').val();
var url = "/Browse/Index";
$.post(url, { id: value });
});
</script>
}
I checked Chrome Debugging tool and Network tab and I see in Preview tab of response that there are no errors and Get Browse/Index action is returning expected results but I don't see them in View. Not sure why.
You make a POST request , but you don't handle the response. For instance, you forget to update the DOM structure.
For doing this, you have to attach a callback function to the returned response.
$.post(url, { id: value },function(response){
//here is request response
});
Also, when you use AJAX, the purpose is to update DOM without refresh page to see the updates.
The solution is to return a JSON object with all the informations and then, handle them in the callback function of $.post method.

using partial view in a view and getting data to partial view

I am using a partial view "_studentList" in a View "SearchStudent". In my View i have a textfield and a search button and i am showing list of students in my partial view.
My View is like as follow:
#model Practice_SQL_Validation_ALL.Models.SearchViewModel
#{
ViewBag.Title = "SearchStudent";
}
<h2>SearchStudent</h2>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand">Search</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" id="txtserch" placeholder="Enter Roll No or Name">
#*#Html.EditorFor(model => model.SEARCHCRITERA.VALUE, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Roll No or Name" } })*#
</div>
<button id="preview" type="button" class="btn btn-default">Search</button>
</form>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div id="result">
#Html.Partial("_StudentList", Model.STUDENTLIST)
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
jQuery.ready(function () {
$("#result").hide();
$("#preview").click(function () {
//$("#div1").hide();
$("#result").show();
});
});
$("#preview").click(function () {
var jsonObject = {
"returnUrl": $('#txtserch').val()
};
jQuery.ajax({
type: "POST",
url: "SearchStudent",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonObject),
success: function (data) { alert("Success"); },
failure: function (errMsg) {
alert("Error");
}
});
});
</script>
And my Partial View is like as follow:
#model IEnumerable<Practice_SQL_Validation_ALL.Models.Student>
#*<p>
#Html.ActionLink("Create New", "Create")
</p>*#
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ROLLNUMBER)
</th>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.ADDRESS)
</th>
<th>
#Html.DisplayNameFor(model => model.PHONE)
</th>
<th>
#Html.DisplayNameFor(model => model.CLASS)
</th>
<th>
#Html.DisplayNameFor(model => model.ISNEW)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ROLLNUMBER)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.ADDRESS)
</td>
<td>
#Html.DisplayFor(modelItem => item.PHONE)
</td>
<td>
#Html.DisplayFor(modelItem => item.CLASS)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISNEW)
</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>
My ViewModel is like as follow:
namespace Practice_SQL_Validation_ALL.Models
{
public class SearchViewModel
{
private SearchCriteria searchcriteria = null;
private List<Student> studentlist = null;
public SearchCriteria SEARCHCRITERA
{
set
{
searchcriteria = value;
}
get
{
return searchcriteria;
}
}
public List<Student> STUDENTLIST
{
set
{
studentlist = value;
}
get
{
return studentlist;
}
}
public SearchViewModel()
{
searchcriteria = new SearchCriteria();
studentlist = new List<Student>();
}
}
public class SearchCriteria
{
[Display(Name = "Criteria")]
public string CRITERIA { get; set; }
[Display(Name = "Value")]
public string VALUE { get; set; }
}
public class Student
{
#region Properties
private bool m_isnew = true;
[Required]
[Display(Name = "Roll Number")]
public string ROLLNUMBER { get; set; }
[Required]
[Display(Name = "Name")]
public string NAME { get; set; }
//[Required]
[Display(Name = "Address")]
public string ADDRESS { get; set; }
//[Required]
[Display(Name = "Phone#")]
public string PHONE { get; set; }
[Display(Name = "Class")]
public string CLASS { get; set; }
[Display(Name = "Edit Mode")]
public bool ISNEW { get { return m_isnew; } set { m_isnew = value; } }
#endregion
}
}
My StudentController is as follow:
namespace Practice_SQL_Validation_ALL.Controllers
{
public class StudentController : Controller
{
public ActionResult SearchStudent()
{
SearchViewModel obj = new SearchViewModel();
ViewBag.Count = 0;
return View(obj);
}
[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//[ChildActionOnly]
public ActionResult SearchStudent(string returnUrl)
{
SearchViewModel obj = new SearchViewModel();
//DAS db = new DAS();
//list = db.SearchStudentwithCriteria("RollNo", "");
//return PartialView()
obj.SEARCHCRITERA.VALUE = "Some";
obj.STUDENTLIST.Add(new Student { ADDRESS = "Address", ROLLNUMBER = "3160", NAME = "Awais", CLASS = "A", PHONE = "Phone" });
//return View(list);
ViewBag.Count = obj.STUDENTLIST.Count;
//return View(obj);
return PartialView("_StudentList", obj);
//return PartialView("_StudentList", list);
//return PartialView("_StudentList", list);
}
}
}
I want that if I click search button then ajax call SearchStudent Post function and return collection that should be displayed on partial view. Till now function is being called but response is not being returned to the view or partialview. As i am showing alertbox in both cases success and failure but system does not show alertbox in anycase. What am i doing wrong? Any help would be greatly appreciated! Please let me know if you need any more information.
Very Thanks in Advance.
Everything seems fine just the ajax succes you have to put the content like this
$.ajax({
url: "SearchStudent",
data: { "returnUrl": $('#txtserch').val()},
type: "POST",
cache: false,
success: function (data) {
$("#result").html(data); //********* This is where you have put the result into, because in success you will get the HTML
},
error: function () {
}
});
Made some changes as follow and got my issue fixed.
In Controller function "SearchStudent" returned partialview with collection.
public ActionResult SearchStudent(string returnUrl)
{
SearchViewModel obj = new SearchViewModel();
obj.SEARCHCRITERA.VALUE = "Some";
obj.STUDENTLIST.Add(new Student { ADDRESS = "Address", ROLLNUMBER = "3160", NAME = "Awais", CLASS = "A", PHONE = "Phone" });
ViewBag.Count = obj.STUDENTLIST.Count;
return PartialView("_StudentList", obj.STUDENTLIST);
}
And changed ajax call as follow:
jQuery.ajax({
type: "POST",
url: "SearchStudent",
//dataType: "json",
cache: false,
//context:
contentType: "html",
data: JSON.stringify(jsonObject),
success: function (data) { $("#result").html(data); },
failure: function (errMsg) {
$("#result").html("Error");
}
});
I think problem was majorly in ajax call. As i was returning html content from controller function but in ajax call i have mentained contentType and datatype properties as Json. That's why HTML could not been shown on success.

Getting a NULL value back for a Model when I see it is NOT NULL during debugging

I have a "Details" View that I am displaying to the user to find out if any statuses are associated with any projects.
When the "GET" for the "Details" view is performed, only a dropdownlist appears asking the user to select an item from the list. In the View, I simply check if the "Model" is null to display the rest of the view or not (the associated projects for that status).
During the "POST", a "status" is retrieved with its associated 'projects'. While coming back into the View, I am expecting the Model not to be null (since it found a status and its associated projects).
If the Model is not null, I want to display the rest of the View.
In the "POST", why is the Model still null? See below code & screenshots. Please copy and paste the screenshot to your favorite image viewer for better viewing.
fyi, after looking in the browser with the debugging tool, I can see that there is no html displayed after the dropdownlist?????
Model
namespace YeagerTechDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
[Serializable, DataContract(IsReference = true)]
public partial class Status
{
public Status()
{
Projects = new HashSet<Project>();
}
[Key]
[ScaffoldColumn(true)]
[DataMember]
public short StatusID { get; set; }
[Required]
[StringLength(30)]
[Display(Name = "Status")]
[DataMember]
public string StatusDescription { get; set; }
[DataMember]
public virtual ICollection<Project> Projects { get; set; }
}
}
JS
$.ajax({
url: Url,
data: JSON.stringify(status_Input),
//data: AddAntiCSRFToken(JSON.stringify(status_Input)),
dataType: "html",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
beforeSend: function ()
{
$('<div id="divLoadMsg" style="text-align:center"><img src="~/Content/progress.gif" /><br/><b>Please wait...</b></div>').dialog({
modal: true, resizable: false, height: 'auto', width: 'auto', minHeight: '30px',
open: function () { $('.ui-dialog-titlebar').hide(); }, close: function () { $('.ui-dialog-titlebar').show(); $(this).dialog('destroy').remove() }
});
},
success: function (data, status)
{
if (status == "success")
{
// Retrieved data
}
},
CONTROLLER
// GET: Statuses/StatusProjects/Details
public ActionResult Details()
{
return View();
}
// POST: Statuses/StatusProjects/Details/5
[HttpPost]
public async Task<ActionResult> Details(short? id)
{
if (id == null)
{
return View("IDIsNull");
}
Status status = await db.GetProjectsByStatusIDAsync(id);
if (status == null)
{
return View("ObjectModelNull");
}
return View();
}
VIEW
#model YeagerTechDB.Models.Status
#using YeagerTechDB.ViewModels.Statuses
#{
ViewBag.Title = "Statuses";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h3>Select Status to see associated Projects</h3>
<div>
#Html.Partial("_SelectStatusProjects", new StatusesDDL());
</div>
#if (Model != null) // Needed for GET
{
<div>
<table class="table table-condensed">
<tr>
<th>
Associated Projects for selected Status
</th>
<th></th>
</tr>
<tr>
<th align="right">Project ID</th>
<th>Project Description</th>
<th>Project Name</th>
<th align="right">Quote</th>
<th>Notes</th>
<th>Created Date</th>
<th>Updated Date</th>
</tr>
<tbody>
#foreach (var item in Model.Projects)
{
<tr>
<td align="right">
#Html.DisplayFor(m => item.ProjectID)
</td>
<td>
#Html.DisplayFor(m => item.Description)
</td>
<td>
#Html.DisplayFor(m => item.Name)
</td>
<td align="right">
#Html.DisplayFor(m => item.Quote)
</td>
<td>
#Html.DisplayFor(m => item.Notes)
</td>
<td>
#Html.DisplayFor(m => item.CreatedDate)
</td>
<td>
#Html.DisplayFor(m => item.UpdatedDate)
</td>
</tr>
}
</tbody>
</table>
</div>
}
EDIT
After making the change that Kundan suggested, I can tell during debugging, if I step through the code, it goes into the View after the POST. The Model is not null and it then properly cycles through the child records that I want displayed on the screen.
However, after that is finished, those records are not displayed on the browser window! The only thing that appears is the dropdownlist again without any display beneath that.
Nothing else is executed after the debugging of the View on the POST which is correct.
The only change that was made in this process is returning the object model of the View (status) as Kundan suggested.
How come the records are not being displayed in the browser after the POST?
fyi, after looking in the browser with the debugging tool, I can see that there is no html displayed after the dropdownlist?????
fyi, I also tried running the page without the dropdownlist and forcing in a value during debugging which would bring back some projects, the same way as if I had selected it from the drop down list. Even with the html removed for the dropdownlist, it went through the View cycled through the collection, but did not emit any html?
Here are the screen shots...
The Model is null because you didn't pass back it to View from your controller. The code should be like below:
[HttpPost]
public async Task<ActionResult> Details(short? id)
{
if (id == null)
{
return View("IDIsNull");
}
Status status = await db.GetProjectsByStatusIDAsync(id);
if (status == null)
{
return View("ObjectModelNull");
}
return View(status);
}
This will fix your issue.

Open Dialog when drop down was changed

I am trying to open a pop up (some dialog) when the user changes the drop down list from the default value which is male to female.I used the JS code from a previous post but nothing happens, in the inspect element I get message that tells me there is no dialog, any idea how to make it work?
I've also tried with an alert but nothing happens either when I change the selection in the drop down list...
I'm very new to JS and Jquery ...
public class Ad
{
public int Name { get; set; }
public string Email { get; set; }
public IEnumerable<SelectListItem> Gender
{
get
{
return new[]
{
new SelectListItem {Value = "M", Text = "Male"},
new SelectListItem {Value = "F", Text = "Female"}
};
}
}
The Index.cshtml code.
#model IEnumerable<Ad.Models.Ad>
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://code.jquery.com/ui/1.9.2/jquery-ui.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#M').change(function () {
if ($(this).val() === "F") {
alert("I am an alert box!");
dialog.dialog('open');
}
});
});
</script>
<h3>My APP</h3>
p>
#using (Html.BeginForm())
{
}
#*<br style="margin-bottom:240px;" />*#
#Html.ActionLink("Create", "Create",
null, htmlAttributes: new { #class = "mybtn" })
<p>
</p>
<style type="text/css">
a.mybtn {
background: #fa0088;
}
</style>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Gender)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DropDownListFor(modelItem => item.Geneder, item.Gender, new { id = "M" })
</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>
Normally the problem occurs when there is no div with an id as 'dialog'. The javascript variable should be initialized as dialog = $('#dialog')
<script type="text/javascript">
$(document).ready(function () {
$("#M").change(function () {
alert($(this).val());
alert($(this).val() == "F");
if ($(this).val() == "F") {
alert("I am an alert box!");
//dialog.dialog('open'); //commenting out this line would tell where the problem lies.
}
});
});
</script>
update: To make it applied to the multiple select boxes, you should use class selector eg .M of jQuery instead of id selector #M. For that first we need to give same class M all the select boxes.
#Html.DropDownListFor(modelItem => item.Geneder, item.Gender, new { id = "M", #class = "M" })
Now change $("#M").change(function () { to $(".M").change(function () {.
$('#M') replace with $('select')

Categories

Resources