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')
Related
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();
I have a foreach to loop through and populate rows in a table. Within the table I have calls to functions and need unique ids to execute the function for each row. It works for the first row as it recognizes the ids for that row but the next row has the same id. What I am trying to do is when the field of one of the rows changes it calculates a value and enters it another field in the corresponding row.
My table is the following
<table class="table">
<tr>
<th></th>
<th class="col1">MFC DRV</th>
<th class="col1">REF Flow (slpm)</th>
<th class="col1">Calibration Flow (slpm)</th>
<th class="col1">% Diff</th>
</tr>
#foreach (var item in Model.DILlist)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.MFC_PointsID, new { htmlAttributes = new { #id = item.MFC_PointsID } })
</td>
<td>
#Html.DropDownListFor(modelItem => item.selectedDRV, item.DRVs, htmlAttributes: new { style = "Width:75px", #id = "mfc" })
</td>
<td>
#Html.EditorFor(modelItem => item.RefFlow, new { htmlAttributes = new { #id = "refFlow", style = "Width:75px", onkeyup = "myFunction(this)" } })
</td>
<td>
#Html.EditorFor(modelItem => item.CalFlow, new { htmlAttributes = new { #id = "calFlow", #disabled = "disabled", style = "Width:75px" } })
</td>
<td>
#Html.EditorFor(modelItem => item.Diff, new { htmlAttributes = new { #id = "Diff", #disabled = "disabled", #class = item.Background, style = "Width:75px" } })
</td>
</tr>
}
<tr>
</table>
and my javascript function
function myFunction(a) {
var number = a.id;
$.ajax({
type: "POST",
//Dev
url: "/CertsHelper/FlowMeterDiffCheck",
//Test and Production
//url: "/RMS_SMM/CertsHelper/FlowMeterDiffCheck",
data: { calFlow: $('#calFlow').val(), refFlow: $('#refFlow').val() },
dataType: "json",
success: function (index) {
$("#Diff").val(index);
if ($("#Diff").val() <= 2 && $("#Diff").val() >= -2) {
$("#Diff").css('background', "lightGreen");
$("#Diff").val(index);
}
else {
$("#Diff").css('background', "indianred");
$("#Diff").val(index);
}
},
error: function (error) {
alert("%Diff not working: " + error);
}
});
}
I think the issue is that you are assigning duplicate IDs to DOM elements. Give each HTML element a unique ID by concatenating the property name and the item ID.
#Html.EditorFor(modelItem => item.RefFlow,
new { htmlAttributes =
new {
#id = $"refFlow_{item.MFC_PointsID}",
style = "Width:75px",
onkeyup = "myFunction(this)"
}
})
#Html.EditorFor(modelItem => item.RefFlow,
new { htmlAttributes =
new {
#id = $"Diff_{item.MFC_PointsID}",
style = "Width:75px"
}
})
In your JavaScript function, retrieve the item ID by splitting the element ID. There are other ways to accomplish this, but for me this approach is straightforward and simple to understand.
function myFunction(a) {
var itemID = a.id.split('_')[1];
...other code...
$('#Diff_' + itemID).val();
}
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.
I am trying to make some blocks of code work from a blank MVC project (no authentication) before applying its logic to my actual project but I can't seem to do it right. I'm trying to have a table in a partial view to reload/refresh/update itself every certain span of time so it'll reflect any changes that was made and that happened in another webpage/browser.
The snippet that fires a function every few second work but the rendering/refreshing is where it gets trippy. I've been following this example with no luck (Refresh Partial View Div in MVC 5).
Here are my code:
View(Index.cshtml)
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<div id="peopletablediv">
#{ Html.RenderAction("Person");}
</div>
Partial View (Person.cshtml)
#model IEnumerable
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<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>
Controller(PeopleController.cs)
public class PeopleController : Controller
{
private WebApplication1Context db = new WebApplication1Context();
// GET: People
public ActionResult Index()
{
return View();
}
public ActionResult Person()
{
return PartialView(db.People.ToList());
}
}
JavaScript(within the index.cshtml only since I'm just testing)
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
var url = '#Url.Action("Person")';
var div = $("#peopletablediv");
setInterval(function () {
div.load(url);
}, 2000);
});
</script>
I've only a few months experience in asp.net MVC and web development in general. Which part would I be getting wrong here?
I have a form consisting of listboxes and radiobuttons. I submit the form through ajax which sends a post. The actionlink in my controller returns a partial view. If the form is invalid I don't want to clear the selected items in the listboxes, but if the form is valid then everything should be unselected. For some reason form.valid() is always true. The error message shows perfectly so I think there is nothing wrong with the validation. Here are some snippets of my code:
View: Form
<div id="researchContainer">
#using (Html.BeginForm("ResearchCompetence", "Planning", FormMethod.Post, new { #id = "researchForm" }))
{
#Html.HiddenFor(x => x.Input.PlanningId)
#Html.ValidationSummary()
<h1>#Html.Label("OverviewResearchCompetences", Labels.OverviewResearchCompetences)</h1>
<table class="table-output">
<thead>
<tr>
<td>#Html.Label("Name", Labels.Name)</td>
<td>#Html.Label("Level", Labels.Level)</td>
<td class="text-align-right"></td>
</tr>
</thead>
<tbody>
#if (Model.CurrentResearchCompetences.Count == 0)
{
<tr>
<td>#Html.Label("NoCurrentCompetencesRes", Labels.NoCurrentCompetencesRes)</td>
</tr>
}
else
{
foreach (var item in Model.CurrentResearchCompetences)
{
<tr>
<td>#item.Vtc</td>
#{
var scoreOutput = new ILVO.Services.EmployeeManagement.ScoreOutput(item.VtcLevel);
}
<td>
#scoreOutput.ToString()
#if (!scoreOutput.ToString().Equals("Gevorderd"))
{
<span class="arrow-up">
#Html.ImageLink("IncreaseLevel", "Planning", new { id = #item.Id, planningId = Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/arrow-icon.png", Labels.IncreaseLevel, "")
</span>
}
#if (!scoreOutput.ToString().Equals("Basis"))
{
#Html.ImageLink("DecreaseLevel", "Planning", new { id = #item.Id, planningId = Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/arrow-icon.png", Labels.DecreaseLevel, "")
}
</td>
<td class="text-align-right deleteLink">
#Html.ImageLink("DeleteVtc", "Planning", new { id = #item.Id, planningId = #Model.Input.PlanningId, actionMethod = "JobCompetence" },
"/Content/delete-icon.png", Labels.Delete, "")
</td>
</tr>
}
}
</tbody>
</table>
<br />
<h1>#Html.Label("AddResearchCompetence", Labels.AddResearchCompetence)</h1>
<table>
<thead>
<tr>
<td>#Html.Label("Disciplines", Labels.Disciplines)</td>
<td>#Html.Label("Organisms", Labels.Organisms) <a id="clear-organisme" class="button-clear-vtc">Clear</a></td>
<td>#Html.Label("Techniques", Labels.Techniques) <a id="clear-technique" class="button-clear-vtc">Clear</a></td>
</tr>
</thead>
<tbody>
<tr>
<td>
#Html.ListBoxFor(x => x.Input.SelectedDiscipline, Model.Disciplines, new { #class = "vtc-listbox-height", #size = 1 })
</td>
<td>
#Html.ListBoxFor(x => x.Input.SelectedOrganism, Model.Organisms, new { #class = "vtc-listbox-height" })
</td>
<td>
#Html.ListBoxFor(x => x.Input.SelectedTechnique, Model.Techniques, new { #class = "vtc-listbox-height" })
</td>
</tr>
</tbody>
</table>
<div id="after-selection-ok">
<h1>#Html.Label("ChooseLevel", Labels.ChooseLevel)</h1>
#Html.RadioButtonFor(x => x.Input.Score, 0, new { #id = "radio1" }) #Html.Label("radio1", Labels.Basic, new { #class = "radio-label" })<br />
#Html.RadioButtonFor(x => x.Input.Score, 1, new { #id = "radio2" }) #Html.Label("radio2", Labels.Intermediate, new { #class = "radio-label" })<br />
#Html.RadioButtonFor(x => x.Input.Score, 2, new { #id = "radio3" }) #Html.Label("radio3", Labels.Expert, new { #class = "radio-label" })<br />
<br />
<input class="button" type="submit" name="AddResearchCompetence" value="#Labels.Submit" />
#Html.ActionLink(Labels.GoBack, "Detail", new { id = #Model.Input.PlanningId }, new { #class = "button margin-left" })
</div>
}
Controller : Actionlink
[HttpPost]
public ActionResult ResearchCompetence(ResearchCompetenceInputModel input)
{
// do some validations
// if validations are ok = add competence else return view
return PartialView("ResearchCompetence", new ResearchCompetenceModel(researchCompetences, currentResearchCompetences, input.PlanningId));
}
My Ajax Call
$("#researchForm").submit(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("ResearchCompetence")',
data: $("#researchForm").serialize(),
success: function (data) {
$("#researchContainer").html(data);
$("#researchForm").validate();
if ($("#researchForm").valid()) { // always true
$("#Input_SelectedOrganism").val('');
$("#Input_SelectedTechnique").val('');
$("input[name='Input.Score']").attr('checked', false);
}
}
});
return false;
});
I also have these scripts loaded:
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/Scripts/jquery-1.10.2.js")
#Scripts.Render("~/Scripts/jquery.validate.min.js")
#Scripts.Render("~/Scripts/jquery.validate.unobtrusive.js")
#Scripts.Render("~/Scripts/jquery-ui-1.10.3.js")
#Scripts.Render("~/Scripts/tinymce/tinymce.min.js")
#Scripts.Render("~/Scripts/ckeditor/ckeditor.js")
#Scripts.Render("~/Scripts/site.js")
#Scripts.Render("~/Scripts/jquery.ui.datepicker-nl-BE.js")