make row clickable after refresh in mvc - javascript

I want to make a row clickable after a refresh. I have this in the view:
#foreach (var item in Model) {
<tr class="#(item.Id == (int)(Session["Id"] ?? 0) ? ".tr.sfs-selected .table.sfs-selectable tbody .dataTable sfs-selected .dataTable sfs-selectable .table-responsive" : String.Empty)" onclick="'<tr>'" data-url="#Url.Action("Index", new RouteValueDictionary { { "id", item.Id } })">
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsEnabled)
</td>
<td>
</tr>
}
I have this jQuery:
$("table.sfs-selectable tbody").on("click", "tr", function (ev) {
var $row = $("tr.sfs-selected").each(function(){
selectRow($row, !$row.hasClass("sfs-selected"));
});
});
However the row is not clicked after refresh.
Thank you
the view:
<table class="table table-striped table-bordered table-hover dataTable sfs-selectable sfs-col1-right-aligned">
<thead>
<tr>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.Id).ToString(), "Sort-Product", new { sortColumn = "id", sortOrder = (ViewBag.sortColumn == "id" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("id", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.Name).ToString(), "Sort-Product", new { sortColumn = "name", sortOrder = (ViewBag.sortColumn == "name" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("name", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.IsEnabled).ToString(), "Sort-Product", new { sortColumn = "enabled", sortOrder = (ViewBag.sortColumn == "enabled" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("enabled", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.FormName).ToString(), "Sort-Product", new { sortColumn = "formname", sortOrder = (ViewBag.sortColumn == "formname" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("formname", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.TemplateName).ToString(), "Sort-Product", new { sortColumn = "design", sortOrder = (ViewBag.sortColumn == "design" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("design", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.RouteLink(Resources.Entity.Product.PublicUrl, "Sort-Product", new { sortColumn = "urlname", sortOrder = (ViewBag.sortColumn == "urlname" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString, filter = ViewBag.Filter })
#ViewHelper.GetSortIndicator("urlname", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th>
#Html.DisplayNameFor(model => firstItem.SubmittedForms)
</th>
<th>
#Html.RouteLink(Html.DisplayNameFor(model => firstItem.ModificationDate).ToString(), "Sort-Product", new { sortColumn = "modified", sortOrder = (ViewBag.sortColumn == "modified" && ViewBag.sortOrder != "desc") ? "desc" : "", searchString = ViewBag.SearchString })
#ViewHelper.GetSortIndicator("modified", ViewBag.sortColumn, ViewBag.sortOrder)
</th>
<th class="hidden"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr class="#(item.Id == (int)(Session["Id"] ?? 0) ? ".tr.sfs-selected .table.sfs-selectable tbody .dataTable sfs-selected .dataTable sfs-selectable .table-responsive" : String.Empty)" data-url="#Url.Action("Index", new RouteValueDictionary { { "id", item.Id } })">
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.IsEnabled)
</td>
<td>
#{
bool viewLink = item.IsEnabled;
if (!String.IsNullOrEmpty(item.FormName)) {
var form = item.FormLibraryEntry;
if (form == null) {
viewLink = false;
#Html.DisplayFor(modelItem => item.FormName)
<em>(#Resources.Entity.Environment.Removed)</em>
}
else {
#Html.DisplayFor(modelItem => form.Name)
<i class="fa fa-fw fa-external-link-square text-info"></i>
}
}
}
</td>
<td>
#{
if (!String.IsNullOrEmpty(item.TemplateName)) {
var template = item.TemplateLibraryEntry;
if (template == null) {
viewLink = false;
#Html.DisplayFor(modelItem => item.TemplateName)
<em>(#Resources.Entity.Environment.Removed)</em>
}
else {
#Html.DisplayFor(modelItem => template.Name)
<i class="fa fa-fw fa-external-link-square text-info"></i>
}
}
}
</td>
<td>
#if (!String.IsNullOrEmpty(item.UrlName)) {
var defaultProductUri = CustomerConfig.ToHostUri(Request.Url.Scheme, defaultHostHeader, Request.Url.Port, (isProduction ? "" : "TEST/") + item.UrlName);
if (viewLink) {
#item.UrlName
<i class="fa fa-fw fa-external-link-square text-info"></i>
}
else {
#item.UrlName
}
}
</td>
<td>
#{
int cnt = item.SubmittedForms.Where(prod => prod.Order.IsProduction == isProduction).Count();
#(cnt.ToString() + " ")
if (cnt > 0) {
<a href="#Url.Action("Index", "SubmittedForms", new { filter = item.Id })">
<i class="fa fa-fw fa-external-link-square text-info"></i>
</a>
}
}
</td>
<td class="text-nowrap">
#item.ModificationDate.ToString("G")
</td>
<td class="hidden">
<span>
#if (!String.IsNullOrEmpty(item.UrlName) && !String.IsNullOrEmpty(item.FormName)) {
#Html.RouteLink(Resources.Action.Navigation.Preview, "ProductPreview", new { productUrl = item.UrlName, customerSchema = custSchema }, new { target = "_blank" })
}
else { #(Resources.Action.Navigation.Preview) }
| #Html.ActionLink(Resources.Action.Navigation.Details, "Details", new { id = item.Id })
| #Html.ActionLink(Resources.Action.Navigation.Edit, "Edit", new { id = item.Id })
</span>
</td>
</tr>
}
</tbody>
</table>
so I have tbody in it. but the problem is now that I have to double click on a row
this is the selectRow function:
function selectRow($row, doSel) {
var $section = $row.closest("section");
if (doSel) {
$section.find("tr.sfs-selected").removeClass("sfs-selected");
$row.addClass("sfs-selected");
$section.find(".sfs-actionbutton").each(function (index) {
var $btn = $(this);
$btn.addClass("disabled");
var href = $row.find("td:last a").filter(function () {
return $(this).text().trim() == $btn.text().trim();
}).attr("href");
if (href) {
$btn.attr("href", href).removeClass("disabled");
if ($btn.parent().is(".btn-group")) {
$btn.parent().children("a").removeClass("disabled");
$btn.attr("data-href", href + "/");
$btn.attr("href", href + "/" + $(".sfs-select-preview-template .active a").attr("href"));
}
}
});
}
else {
$row.removeClass("sfs-selected");
$section.find(".sfs-actionbutton").addClass("disabled");
}
}

You just have wrong selector, i gess it should be like this:
var $row = $("tr.sfs-selected").each(function(){
selectRow( $(this), $(this).hasClass("sfs-selected"));
});
The point is in each() method you can get one of collection element with this keyword.

You seem to be specifying class names by adding leading dots . to them, but I don't think you mean to have them like that (or the jQuery selectors won't work). Also the inline onclick is not in a working state, but your jQuery event should take care of that so that can be removed.
<tr class="#(item.Id == (int)(Session["Id"] ?? 0) ? "sfs-selected sfs-selectable" : String.Empty)" data-url="#Url.Action("Index", new RouteValueDictionary { { "id", item.Id } })">
Now, I am assuming you don't really want a classes named tbody dataTable table-responsive on each row either, so I removed them. They should probably be set on the <table> and/or <tbody> but if you need them back just re-add them.
For you jQuery:
The call to selectRow() seems a bit odd, since it will only iterate table rows with class sfs-selected, hence it will always call the function with selectRow($(element), false).
In other words: when you click a table row any row with class sfs-selected will have it's class removed and actionbutton will be disabled. Is this the desired behavior?

Related

Making load more function in Vue

Trying to make a load more button, when user click it add 10 more item into the page. But the button code is not running smoothly... I still see all items in the page, and also there is no error in the console too.. of course button is not working.
Additionally, trying to make it run with the filter function.. Thank you for any example, help.
data() {
return {
estates:[],
moreEstates: [],
moreEstFetched: false,
}
},
mounted() {
axios.get('/ajax').then((response) => {
this.estates = response.data
this.insertMarkers();
});
},
methods: {
handleButton: function () {
if(!this.moreEstFetched){
axios.get('/ajax').then((response) => {
this.moreEstates = response.data;
this.estates = this.moreEstates.splice(0, 10);
this.moreEstFetched = true;
});
}
var nextEsts = this.moreEstFetched.splice(0, 10);
this.estates.push(nextEsts);
},
},
computed: {
one: function () {
let filteredStates = this.estates.filter((estate) => {
return (this.keyword.length === 0 || estate.address.includes(this.keyword)) &&
(this.rooms.length === 0 || this.rooms.includes(estate.rooms)) &&
(this.regions.length === 0 || this.regions.includes(estate.region))});
if(this.sortType == 'price') {
filteredStates = filteredStates.sort((prev, curr) => prev.price - curr.price);
}
if(this.sortType == 'created_at') {
filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
}
filteredStates = filteredStates.filter((estate) => { return estate.price <= this.slider.value});
filteredStates = filteredStates.filter((estate) => { return estate.extend <= this.sliderX.value});
filteredStates = filteredStates.filter((estate) => { return estate.m2_price <= this.sliderT.value});
return filteredStates;
},
},
<table class="table table-hover">
<thead>
<tr style="background-color: #fff ">
<th scope="col">イメージ</th>
<th style="width:175px;"scope="col">物件名</th>
<th style="width:175px;"scope="col">住所</th>
<th scope="col">販売価格</th>
<th scope="col">間取り</th>
<th scope="col">専有面積</th>
<th scope="col">坪単価</th>
<th style="width:90px;" scope="col">物件詳細</th>
</tr>
</thead>
<tbody>
<tr  v-for="estate in one">
<td><img id="image" :src="estate.image" alt=""></td>
<td>{{estate.building_name}}</td>
<td>{{estate.address}}</td>
<td>{{priceSep(estate.price)}} 万円</td>
<td>{{estate.rooms}}</td>
<td>{{xtendSep(estate.extend)}} m²</td>
<td>{{estate.m2_price}}</td>
<td><a :href="/pages/+estate.id">物件詳細</a></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary loadmorebutton" #click="handleButton">Load more</button>
As #pyriand3r pointed out that the axios request is async you can do something like this with async/await without modifiyng too much the code.
methods: {
handleButton: function () {
if(!this.moreEstFetched){
axios.get('/ajax').then(async (response) => {
this.moreEstates = await response.data;
this.estates = this.moreEstates.splice(0, 10);
this.moreEstFetched = true;
});
}
// Also you cant splice a boolean only arrays.
var nextEsts = this.moreEstFetched.splice(0, 10);
this.estates.push(nextEsts);
},
},
See: Async/await in JavaScript
Made some changes to your code, read the comment to understand.
But this is the same as the last post you added.
data() {
return {
visible:true ,
estates:[],
moreEstates: [],
moreEstFetched: false,
size: 10,
selectedPage:0,
init: false,
}
},
updated: function () { // when loaded, trigger only once
if (!this.init) {
this.handleButton();
this.init = true;
}
},
mounted() {
// why is this here, you should only have handleButton to load the data
// axios.get('/ajax').then((response) => {
// this.estates =this.filterData(response.data)
// this.insertMarkers();
// this.showMore();
// });
},
methods: {
filterData: function (data) {
let filteredStates = data.filter((estate) => {
return (this.keyword.length === 0 || estate.address.includes(this.keyword)) &&
(this.rooms.length === 0 || this.rooms.includes(estate.rooms)) &&
(this.regions.length === 0 || this.regions.includes(estate.region))});
if(this.sortType == 'price') {
filteredStates = filteredStates.sort((prev, curr) => prev.price - curr.price);
}
if(this.sortType == 'created_at') {
filteredStates = filteredStates.sort((prev, curr) => Date.parse(curr.created_at) - Date.parse(prev.created_at));
}
filteredStates = filteredStates.filter((estate) => { return estate.price <= this.slider.value});
filteredStates = filteredStates.filter((estate) => { return estate.extend <= this.sliderX.value});
filteredStates = filteredStates.filter((estate) => { return estate.m2_price <= this.sliderT.value});
return filteredStates;
},
showMore: function(){
if (Math.ceil( this.moreEstates.length / this.size) <= this.selectedPage +1 ){
this.selectedPage++;
// using slice is better where splice changes the orginal array
var nextEsts = this.moreEstFetched.slice((this.selectedPage * this.size), this.size);
this.estates.push(nextEsts);
}else this. visible= true; // hide show more
},
handleButton: function () {
if(!this.moreEstFetched){
axios.get('/ajax').then((response) => {
// filter the whole data at once
this.moreEstates = this.filterData(response.data);
this.moreEstFetched = true;
// not sure what this is, i moved it here
this.insertMarkers();
this.showMore();
});
}else this.showMore();
},
},
<table class="table table-hover">
<thead>
<tr style="background-color: #fff ">
<th scope="col">イメージ</th>
<th style="width:175px;"scope="col">物件名</th>
<th style="width:175px;"scope="col">住所</th>
<th scope="col">販売価格</th>
<th scope="col">間取り</th>
<th scope="col">専有面積</th>
<th scope="col">坪単価</th>
<th style="width:90px;" scope="col">物件詳細</th>
</tr>
</thead>
<tbody>
<tr v-for="estate in estates">
<td><img id="image" :src="estate.image" alt=""></td>
<td>{{estate.building_name}}</td>
<td>{{estate.address}}</td>
<td>{{priceSep(estate.price)}} 万円</td>
<td>{{estate.rooms}}</td>
<td>{{xtendSep(estate.extend)}} m²</td>
<td>{{estate.m2_price}}</td>
<td><a :href="/pages/+estate.id">物件詳細</a></td>
</tr>
</tbody>
</table>
<button v-if="visible" class="btn btn-primary loadmorebutton" #click="handleButton">Load more</button>
actually, I am not sure it is the best way but, tried much more simplest way to achieve it...
data() {
return {
moreEstates: 10,
}
},
<table class="table table-hover">
<tbody>
<tr v-if="moreIndex < one.length"  v-for="moreIndex in moreEstates">
<td><img id="image" :src="one[moreIndex].image" alt=""></td>
<td>{{one[moreIndex].building_name}}</td>
<td>{{one[moreIndex].address}}</td>
<td>{{priceSep(one[moreIndex].price)}} 万円</td>
<td>{{one[moreIndex].rooms}}</td>
<td>{{xtendSep(one[moreIndex].extend)}} m²</td>
<td>{{one[moreIndex].m2_price}}</td>
<td><a :href="/pages/+one[moreIndex].id">物件詳細</a></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary loadmorebutton" #click="moreEstates += 10">次の10件を見る</button>

Passing a Parameter to Javascript Function for ajax in mvc

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();

Checkbox check selection in MVC Razor table is coming as false

I have below table -
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => modelItem[i].ShouldImport, new { #class = "sid", #onclick = "DisplayDetailedInfo(this)" })
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].Name)
#Html.HiddenFor(modelItem => modelItem[i].Name)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].AccountNumber)
#Html.HiddenFor(modelItem => modelItem[i].AccountNumber)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].AccountType)
#Html.HiddenFor(modelItem => modelItem[i].AccountType)
</td>
<td>
#Html.DisplayFor(modelItem => modelItem[i].AccountStatus)
#Html.HiddenFor(modelItem => modelItem[i].AccountStatus)
</td>
<td>
#Html.CheckBoxFor(modelItem => modelItem[i].IsLatePayment)
</td>
</tr>
}
My Javascript Function is follows -
function DisplayDetailedInfo(data) {
console.log(data);
var vval = $(data).val();
var anotherval = $(this).is(':checked')
console.log(anotherval);
if (anotherval)
{
console.log("Hi");
}
}
I need assistance why I am getting value as false although I am checking the Checkbox. I am new to razor and Jquery and need assistance.
The keyword this in your case is returning window so you have to replace it with data as follows:
function DisplayDetailedInfo(data) {
console.log(data);
var vval = $(data).val();
var anotherval = $(data).is(':checked');
console.log(anotherval);
if (anotherval)
{
console.log("Hi");
}
}

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')

form.valid() returns true when form is invalid

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")

Categories

Resources