checkbox value is always true - asp.net-mvc-3

in my mvc application i have a checkbox. but dont know why its value is always true. pls help
my view page
<div id="maindiv">
<%: Html.CheckBoxFor(m => m.status)%>
<%: Html.LabelFor(m => m.status)%>
</div>
and the script is here how i am getting the value TRUE always
<script type="text/javascript">
$('#status').change(function () {
alert(" active " + $('#status').val());
});
</script>

use instead:
var status = ( $("#status").attr("checked") ? 'checked' : 'unchecked' );
alert(" active " + status);
Explanation:
you were reading the value of the checkbox which is always true, you need to check whether its checked attribute is checked or unchecked.
I used the ternary operator to check check whether it's checked or not
You could have also used $("#status").is(":checked") but it is slower.

$('#status').change(function () {
alert(" active " + this.checked);
});

I recommend this answer by Jab because it works.
var myValue = $("#status").is(":checked");
If checked, myValue = true, else myValue = false.

Related

Conditional v-if is working only for the first time?

I have this in my view:
<div class="already_voted" v-if="already_voted" >
<p>You already voted or your are not allowed to vote</p>
</div>
This is my method :
upvote: function(com_id) {
var comment_id = {
comment_id :com_id
}
this.$http.post('/blog/article/comment/upvote', comment_id).then(function(response){
upvote_total= response.data.upvote_value;
this.already_voted = response.data.already_voted;
this.$dispatch('child-msg', this.already_voted);
$('.upvote_class_' + com_id ).text(upvote_total);
$('.isDisabledUpvote_' + com_id).addClass('disabled');
$('.isDisabledDownvote_' + com_id).removeClass('disabled');
},function(response){
});
},
Im getting value on click and if its true it need to show this div.
Problem is that this div is showed only for first time when already_voted is true and thats it. Next time when its true nothing happend. Any suggestion?
It looks like you are mixing jQuery and Vue, which should be avoided unless you have a specific reason to do so. Instead you should bind attributes to data. As a basic version of what you are doing you could bind both the disabled attribute and the message to a voted flag:
Markup
<div id="app">
<div v-if="voted">
You have already voted!
</div>
<button v-bind:disabled="voted" #click="vote()">
Vote
</button>
<button v-bind:disabled="!voted" #click="removeVote()">
Un-Vote
</button>
</div>
View Model
new Vue({
el: '#app',
methods: {
vote(){
this.voted = true;
},
removeVote(){
this.voted = false;
}
},
data: {
voted: false
}
});
Here I'm simply binding the disabled attribute using v-bind to the voted flag to disabled the buttons and am using v-if to show a message if the voted flag is true.
Here's the JSFiddle: https://jsfiddle.net/05sbjqLL/
Also be aware that this inside an anonymous function refers to the anonymous function itself, so either assign this to something (var self = this) outside the function or use an arrow function if using ES6.
EDIT
I've updated the JSFiddle to show you how you might handle your situation based on you comments:
https://jsfiddle.net/umkvps5g/
Firstly, I've created a directive that will allow you to initiate your variable from your cookie:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
})
This can now be used as:
<div v-init:voted="{{ $request->cookie('voted') }}"></div>
I simply disabled the button to show you how to bind attributes to data, there's loads more that can be done, for example showing the message after a user clicks the button, I've just added a click counter and bound thev-if to that instead, so the message doesn't show until a user clicks the button:
<div v-if="vote_attempts">
You have already voted!
</div>
Then in vote() method:
vote() {
this.voted = true;
this.vote_attempts++;
},
Then data:
data: {
voted: false,
vote_attempts: 0
}

toastr js is not showing toasts

I am using toastr.js for notification, my drop down code is
<%= Html.DropDownListFor(m => m.MakeText, Model.MakeSelect, string.Empty, new { data_bind = "optionsText: Make,value: Make", Id = "ddMake", style = "width: 200px;font-size: 20px" })%>
and in site typescript is
$(document).ready(function () {
viewModel.Make.subscribe(function (item) {
item && toastr.success('selected make');
});
)}
but problem is i can not see toasts, once i implement only
toastr.success('selected make')
its work good, Can you please tell me what is the issue in subscribe code.
Thanks
item is falsy. That would mean item && toastr.success('selected make'); gets short-circuited and toastr.success('selected make'); is never evaluated.

jQuery unobtrusive validation in .NET MVC 3 - showing success checkmark

Using jQuery unobtrusive validation within a .NET MVC project and that seems to be working fine. I'm now trying to show a green checkmark when the field validates correctly (client-side and/or remote).
Here's a sample field declaration:
<div class="clearfix">
#Html.LabelFor(model => model.Address1, "Street")
<div class="input">
#Html.TextBoxFor(model => model.Address1, new { #class = "xlarge", #maxlength = "100", #placeholder = "e.g. 123 Main St" })
<span class="help-message">
#Html.ValidationMessageFor(model => model.Address1)
<span class="isaok">Looks great.</span>
</span>
<span class="help-block">Enter the street.</span>
</div>
</div>
What I'd like to do is add a class 'active' to the "span.isaok" which in turn has a checkmark for a background image.
I tried using highlight/unhighlight:
$.validator.setDefaults({
onkeyup: false,
highlight: function (element, errorClass, validClass) {
$(element).addClass(errorClass).removeClass(validClass);
$(element.form).find("label[for=" + element.id + "]").addClass("error");
$(element).parent().find("span.isaok").removeClass("active");
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass);
$(element.form).find("label[for=" + element.id + "]").removeClass("error");
if ($(element).val().length > 0) {
$(element).parent().find("span.isaok").addClass("active");
}
}
});
but that shows a green checkmark for all fields even if they're empty! (hence obviously wrong)
I then tried using the 'success' option but that never seems to be fired.
What am I missing?
Edit: So I found this blog post and was able to tap into the success function i.e.
$(function () {
var settings = $.data($('form')[0], 'validator').settings;
settings.onkeyup = false;
settings.onfocusout = function (element) { $(element).valid(); };
var oldErrorFunction = settings.errorPlacement;
var oldSuccessFunction = settings.success;
settings.errorPlacement = function (error, inputElement) {
inputElement.parent().find("span.isaok").removeClass("active");
oldErrorFunction(error, inputElement);
};
settings.success = function (label) {
var elementId = '#' + label.attr("for");
$(elementId).parent().find("span.isaok").addClass("active");
oldSuccessFunction(label);
};
});
but now if the form isn't valid it shows both the error message and the valid mark...
and the latter disappears as soon as I click anywhere on the page.
This appears to be an issue with the jquery.validate.unobtrusive interfering with the settings added later in $.validator.setDefault. The trick is to load the unobtrusive script after the custom settings. See here and vote to fix it here.
In case any one has a similar problem, I finally got this working by using the un-minified version of jquery.validate.unobtrusive.js and adding my js to the onError and onSuccess methods. Existing code was left as it. Use the re-minified version during deployment.
Thanks.
This is not a direct answer to your question. I am going to offer an alternative approach to this: TwitterBootstrapMVC.
With this library all you'd have to write for each input is:
#Html.Bootstrap().ControlGroup().TextBoxFor(m => m.Address1)
And that's it. You will have label, input, and validation message - all taken care of, without javascript. It generates proper html mark up for you. You just need to make sure that you have proper standard css for classes like .field-validation-error, .field-validation-valid...

How do I set a checkbox in razor view?

I need to check a checkbox by default:
I tried all of these, nothing is checking my checkbox -
#Html.CheckBoxFor(m => m.AllowRating, new { #value = "true" })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = "true" })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = true })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = "checked"})
You should set the AllowRating property to true, preferably in the controller or model.
Like other inputs, the checkbox's state reflects the value of the property.
This works for me:
<input id="AllowRating" type="checkbox" #(Model.AllowRating?"checked='checked'":"") style="" onchange="" />
If you really wants to use HTML Helpers:
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = Model.AllowRating})
Also take into account that if m.AllowRating is false, it will fail to set to status checked in your examples.
The syntax in your last line is correct.
#Html.CheckBoxFor(x => x.Test, new { #checked = "checked" })
That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.
You can do this with #Html.CheckBoxFor():
#Html.CheckBoxFor(m => m.AllowRating, new{#checked=true });
or you can also do this with a simple #Html.CheckBox():
#Html.CheckBox("AllowRating", true) ;
you set AllowRating property to true from your controller or model
#Html.CheckBoxFor(m => m.AllowRating, new { #checked =Model.AllowRating })
<input type="checkbox" #( Model.Checked == true ? "checked" : "" ) />
only option is to set the value in the controller, If your view is Create then in the
controller action add the empty model, and set the value like,
Public ActionResult Create()
{
UserRating ur = new UserRating();
ur.AllowRating = true;
return View(ur);
}
If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database.
form of it:
#Html.CheckBox("NameOfVarInModel", true) ;
for you!
#Html.CheckBox("AllowRating", true) ;
I had the same issue, luckily I found the below code
#Html.CheckBoxFor(model => model.As, htmlAttributes: new { #checked = true} )
Check Box Checked By Default - Razor Solution
I did it using Razor , works for me
Razor Code
#Html.CheckBox("CashOnDelivery", CashOnDelivery) (This is a bit or bool value) Razor don't support nullable bool
#Html.CheckBox("OnlinePayment", OnlinePayment)
C# Code
var CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
var OnlinePayment = Convert.ToBoolean(Collection["OnlinePayment"].Contains("true") ? true : false);

ASP.NET MVC 3 WebGrid - Conditional Column Formatting

Is there anyway to do conditional formatting with Webgrid in ASP.NET MVC 3?
I know I can say:
... grid.Column("PropertyName", "Header Name", style: "bold") ...
and it will render HTML that for the TD that says: class="bold".
What I want, is to render some TDs in one style and other TDs in another style. Like:
... grid.Column("PropertyName", "Header Name", style: (item) => (item.Property > 100) ? "bold" : "normal")) ....
but this causes the error "Best overloaded method match ... has some invalid arguments."
Any idea if this is possible?
Thanks
.Jim Biddison
I know I'm kind of late with the answer, but if someone is still looking for that kind of conditional formating / column value binding for WebGrid here's somehting that works :
#grid.GetHtml(
columns: grid.Columns(
grid.Column(format: (item) => (item.someproperty !=null) ?
Html.Raw("I've got value") :
Html.Raw("I don't :("))
)
)
You can do this with some JQuery:
<script type='text/javascript'>
$(document).ready(function () {
jQuery.each($('tbody tr td'), function () {
if (this.textContent == "some value") {
$(this).addClass("some class");
}
});
});
</script>
Of course, you'll have to modify the logic inside the each loop...
Hope that helps.
I don't think the style property accepts functions. You can use jQuery or here is a hack:
Hack
For googler, an improved version of the Torm answer:
#grid.GetHtml(
columns: new[]
{
grid.Column(format:item => Html.Raw("<span" + (item.Property > 100 ? " style='bold'" : "") + ">" + item.Property + "</span>")),
}
)

Resources