Id with RadioButtonFor - c#

I'm trying to deal with radiobutton ids in asp MVC 5
I'm working like this
Example model
class A
{
public bool? radio { get; set; }
}
and in razor view
#Html.RadioButtonFor(x => x.NeutroBT, Model.NeutroBT, new { #id = "True"})
#Html.RadioButtonFor(x => x.NeutroBT, !Model.NeutroBT, new { #id = "False})
It doesn't cause problem, but I'm working in an editortemplate, and I want it to have generated id, to access in some way like #Html.IdFor(x => x.NeutroBT, true) and #Html.IdFor(x => x.NeutroBT, false) from the other views, just preventing changes in the future
Is some like this possible? I pass a lot of time searching and I didn't get anything similar
If is not possible, what is the best way to deal with it?
thanks!

There is no need to use an id attribute. Instead you can just use the name attribute to select or set the value via javascript (and in any case, #Html.IdFor() will only ever returnNeutroBT, not theidthat you override in theRadioButtonFor()` method so it cannot be used in your case)
In addition, the 2nd parameter of RadioButtonFor() should be true or false (not Model.NeutroBT and !Model.NeutroBT).
And to associate a label with the button, you can wrap it in a <label>, for example
<label>
#Html.RadioButtonFor(x => x.NeutroBT, true, new { id = ""})
<span>Yes</span>
</label>
<label>
#Html.RadioButtonFor(x => x.NeutroBT, false, new { id = ""})
<span>No</span>
</label>
Note that new { id = "" } removes the id attribute and prevents invalid html due to duplicate id attributes.
Then to access the selected value using jQuery
var selectedValue = $('input[name="' + #Html.NameFor(x => x.NeutroBT) + '"]:checked').val();

Related

How to take value from DataValueField() of a Kendo().DropDownList() on change event

I'm using kendo grid and editor template for showing my data. in editor I've given id to DataValueField() and name to DataTextField() of kendo dropdown list. In change event, I'm not able to get the DataValueField(). see the following code
This is my editor template MemoCarrier.chtml
#using System.Collections
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
.Events(e =>
{
e.Change("MemoCarrier");
})
)
Here is my on change function
function MemoCarrier(e) {
var AirlineName = this.value();
alert(AirlineName) //it displays PARTNERNAME instead of PARTNERID
}
Currently I'm getting name ie;DataTextField() value. instead of that, I need DataValueField().
Thanks for suggestions in advance!
so based on your comment the easiest way to do this would probably use the data-bind attribute to simplify the process of binding the model. Assuming you are using the MVC helper for the grid as well.
so taking your code and adding this:
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum", data_bind="value:{yourProperyNameHere}" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
)
So hopefully you can see all I am doing is adding a new HtmlAttribute property to the control for you. All you need to do is put whatever property is meant to be the value for this.
Depending on if this value is a complex (object) or simple (string, int etc) primitive type you may need to set the Primitive property to true so that only the valuefield e.g the id you are assigning is bound back to the grid's row model.

Losing complete Model when posting Ajax values to controller

What i want to do is have 2 listboxes (left, right) where left would have all products entities except the ones that are present in my Contract Entity and in the right the products in my Contract Entity.
I am having this issue that when i pass 1 parameter (string) I can receive them correctly in my controller but whenever i pass my model with it as a second parameter i loose my model completely. This is what i have:
Controller:
public ActionResult EditContract(ContractViewModel model, string selectedProducts)
View (Javascript/JQuery):
function GetSelectedProducts() {
var listbox = document.getElementById("productsForContractListbox");
var txt = "";
var i;
for (i = 0; i < listbox.length; i++) {
txt = txt + "\n" + listbox.options[i].text;
}
$('#SelectedProductForContracts').val(txt);
var selectedProducts = $('#SelectedProductForContracts').val();
var model = $('form').serialize;
$.post('#Url.Action("EditContract", "Contract")', { "model": model, "selectedProducts": selectedProducts});
}
Html helper listboxes:
// listbox for my contract products
#Html.ListBoxFor(c => c.Contract.Products, productsForContract, new { ID = "productsForContractListbox", #class = "form-control" })
// listbox where all products except the ones in my contract are loaded
#Html.ListBox("allProducts", allProducts, new { ID = "allProductsListbox", #class = "form-control" })
HiddenFor for the SelectedProductForContracts from my Model:
#Html.HiddenFor(c => c.SelectedProductForContracts, new { ID = "SelectedProductForContracts", name = "SelectedProductForContracts" })
Model:
[HiddenInput(DisplayValue = false)]
public List<SelectListItem> SelectedProductForContracts { get; set; }
When having the post data containing only the selectedProducts, i get my values but lose my model, when i add my model i get my model but lose my selectedProducts values.
I tried several things like THIS but couldn't get them to work in my case (i am doing something wrong probably but don't know what ...)
Can anyone help me towards the proper way of achieving this cause i see many ways but i hope there must be an elegant way of binding everything to 1 model without having to use javascript/Jquery ?
Kind regards!
List<SelectListItem> is not able to be defined in a single hidden variable

MultiLineText DataType Value not populating in TextAreaFor

I am attempting to implement an Update on a current text area value.
The datatype is set for multiline in my model
[DataType(DataType.MultilineText)]
public string Text { get; set; }
When the page loads for the textarea, it does not populate.
#Html.TextAreaFor(a => a.Text, new { #Value = Model.Text })
But for a textbox it does populate
#Html.TextBoxFor(a => a.Text, new { #Value = Model.Text })
Is there something I'm missing? this seems pretty straight forward.
#Html.TextAreaFor(a => a.Text, new { id = "SomeID", placeholder = "Text", Value = Model.Text})
#Html.TextAreaFor(m => m.UserName) should be enough - ASP MVC takes care of populate current value from model to textarea.
Using { #Value = Model.Text } doesn't apply to textarea as it does not uses value attribute: How to add default value for html <textarea>?

RadioButton comes checked automatically

I used RadioButtonFor like this
#Html.RadioButtonFor(m => m.Content, Model.Content, new { #name = "rb", #class = "answer-radio", #id = "answer-" + Model.Counter,#checked = "false" })
#Html.Label(Model.Content, new { #for = "answer-" + Model.Counter })
#Html.HiddenFor(m => m.Content)
But this radiobutton comes "checked". How can i disable it ?
Are you sure you want a radio button? Seems like you might be after a Checkbox...
For a boolean, I would set up a 2 radiobuttons like so:
#Html.RadioButtonFor(m => m.Content, true, new { #id = "rb1" })
#Html.RadioButtonFor(m => m.Content, false, new { #id = "rb2" })
The html helper will figure out which one to check. If Model.Content is of another type, use different values for the radiobuttons and MVC will still figure out which one to check.
Edit:
Actually, it's even simpler than that. If the you use the Html helper RadioButtonFor method, it will check the radiobutton if it finds a value that matches the Model property. So you've specified your RadioButton as always having the same value as your Model property so it will always be checked (and that is the value that will be posted back in the form)
So, if you wanted a bool to default to false, and only return true if checked you could do just this:
#Html.RadioButtonFor(m => m.Content, true, new { #id = "rb1" })
where Content is originally set to false.
You can do it with other value types as well. e.g. if Content was a string, initially set to null, this would post back "RadioButtonChecked" only if the radio button was checked. Null otherwise:
#Html.RadioButtonFor(m => m.Content, "RadioButtonChecked", new { #id = "rb1" })
Adding "checked" to the attribute list will make it checked no matter what. I would make sure the value in your model is either null or false.

Add Id or other attributes to ASP.NET MVC 3 Html Helper Textbox

How can I add attributes to a html helper textbox.
I've tried this:
#Html.TextBox("username", new { id = "username" })
This seems to put 'id=username' in the value field of the textbox. I want to add an Id to my textbox.
Thanks.
The second parameter (new { id = "username" } in your example) is the initial value (value attribute) of the TextBox. The third parameter is the actual htmlAttributes:
#Html.TextBox("username", Model.Username, new { id = "username" })
while new { id = "username" } as the 2nd parameter is valid, you will need to add # to attributes that are also keywords, like class.

Categories

Resources