Passing parameters to MVC Ajax.ActionLink - asp.net-mvc-2

How can I send the value of the TextBox as a parameter of the ActionLink?
I need to use the Html.TextBoxFor
<%= Html.TextBoxFor(m => m.SomeField)%>
<%= Ajax.ActionLink("Link Text", "MyAction", "MyController", new { foo = "I need here the content of the textBox, I mean the 'SomeField' value"}, new AjaxOptions{ UpdateTargetId = "updateTargetId"} )%>
The Contoller/Actions looks like this:
public class MyController{
public ActionResult MyAction(string foo)
{
/* return your content */
}
}
Using MVC 2.0

How can I send the value of the TextBox as a parameter of the ActionLink?
The semantically correct way of sending input fields values (such as textboxes) to a server is by using an html <form> and not links:
<% using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions { UpdateTargetId = "updateTargetId" })) { %>
<%= Html.TextBoxFor(m => m.SomeField) %>
<input type="submit" value="Link Text" />
<% } %>
Now in your controller action you will automatically get the value of the SomeField input entered by the user:
public class MyController: Controller
{
public ActionResult MyAction(string someField)
{
/* return your content */
}
}
You could of course try to violate the markup semantics and the way HTML is supposed to work by insisting on using an ActionLink even if it is wrong. In this case here's what you could do:
<%= Html.TextBoxFor(m => m.SomeField) %>
<%= Html.ActionLink("Link Text", "MyAction", "MyController", null, new { id = "myLink" }) %>
and then in a separate javascript file unobtrusively AJAXify this link using jQuery:
$(function() {
$('#myLink').click(function() {
var value = $('#SomeField').val();
$('#updateTargetId').load(this.href, { someField: value });
return false;
});
});

Related

How can I send a single string value through View Form in my webAPI?

How can I send a single string value through view from in the WebAPI made in ASP.NET core.
Here is my API:
[HttpPost]
[Route("studentlogin/{value}")]
public IActionResult StudentLogin(string value)
{
string name = String.Concat(value.Where(s => !Char.IsWhiteSpace(s)));
name = name.ToLower();
var newStudent = new Student();
newStudent.FullName = name;
db.Entry(newStudent).State = EntityState.Added;
db.SaveChanges();
var selectStudent = db.Students.Where(ss => ss.FullName == name).FirstOrDefault();
var id = selectStudent.Id;
string idToString = id.ToString();
string answer = sha384converter(idToString);
selectStudent.HashId = answer;
db.Entry(selectStudent).State = EntityState.Modified;
db.SaveChanges();
return Ok();
}
I want to send paramenter value in it through View Forms, How can I send data in it?
Thanks in advance.
[Route("studentlogin/{value}")]
If you are using the above route, the request URL should like this: https://localhost:44310/api/apicontrollername/studentlogin/XXX, the parameter will be transferred from the URL and route.
to send paramenter value in it through View Forms, How can I send data
in it?
To send parameter value from posted form fields, you could modify the code as below:
In the API controller, remote the route parameter and add the FromForm attribute.
[HttpPost]
[Route("studentlogin")]
public IActionResult StudentLogin([FromForm]string value)
{
string name = "Default value";
if (!string.IsNullOrEmpty(value))
{
name = String.Concat(value.Where(s => !Char.IsWhiteSpace(s)));
}
... // add your code
return Ok(name);
}
Then, create a model which contain the value property, like this:
public class StudentLoginViewModel
{
public string value { get; set; }
}
In the View page, display the above model in the form:
#model WebApplication6.Models.StudentLoginViewModel;
<form id="myform">
<div class="form-group">
<label asp-for="value" class="control-label"></label>
<input asp-for="value" class="form-control" />
<span asp-validation-for="value" class="text-danger"></span>
</div>
<div class="form-group">
<input type="button" id="btnsubmit" value="Submit" class="btn btn-primary" />
</div>
</form>
and add the following script at the end of the above view page:
#section Scripts{
<script>
$(function () {
$("#btnsubmit").click(function () {
//use the serialize() method to encode a set of form elements as a string for submission
var data = $("#myform").serialize();
//you can also create JavaScript object and send the data.
//var data = { value: $("#value").val() };
$.ajax({
url: '/api/todo/studentlogin', // change the url to yours.
type: "post",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});
});
})
</script>
}
The result as below:

Editing IEnumerable Model Property in MVC View

I have a situation where I need to edit an enumerable property in a view model:
public class ViewModel
{
public MyObj Obj { get; set; }
public IEnumerable<MyObj> MyObjs = new List<MyObj>();
}
I have followed this post; controller action:
public ActionResult Index()
{
var viewModel = new ViewModel();
viewModel.Obj = new Obj() { Name = "0", Value = true };
var o1 = new MyObj() { Name = "1", Value = false };
var o2 = new MyObj() { Name = "2", Value = false };
viewModel.Objs = new List<Obj>() { o1, o2 };
return View(viewModel);
}
[HttpPost]
public ActionResult Index(ViewModel viewModel)
{
return View(viewModel);
}
The Index view as follows:
<% using (Html.BeginForm()) { %>
<table>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<%= Html.EditorFor(x => x.Objs) %>
</table>
<br />
<input type="submit" value="Submit" />
<% } %>
And the editor template in "~/Views/Home/EditorTemplates/Obj.ascx":
<tr>
<td><%: Html.TextBoxFor(x => x.Name) %></td>
<td><%: Html.CheckBoxFor(x => x.Value) %></td>
</tr>
The issue is: browse to Index, the data shows up. The POST, and the enumerable data disappears. Stepping through, the singular "Obj" in the view model remains, so it is just the enumerable data that is disappearing.
I have been staring at this for some time now, if any one could help out it would be brilliant.
Cheers,
Tim.
Take a look at this post by Phil Haack, MVC2 doesn't natively support binding a list back to the viewmodel unless you do a little manipulation.
Update: I've looked into this a little more and think you should try adding TryUpdateModel(viewModel.MyObjs, "MyObjs"); to your Controller. This informs the modelbinder that it should use the "MyObjs" binding prefix to attach the data from the form to the collection in your ViewModel.

Images being displayed as weird characters

In this project I'm trying to implement a price list (it's a taxidermy site) So here's what I'm going to do, show you the code
PriceListController
public partial class PriceListController : Controller
{
public PriceListController()
{
}
[CanonicalUrlAttribute("PriceList")]
[CompressionFilter(Order = 1)]
[CacheFilter(Duration = 120, Order = 1)]
public virtual ActionResult Index()
{
GodsCreationTaxidermyEntities context = new GodsCreationTaxidermyEntities();
var viewModel = new PriceListViewModel() { PriceListAnimals = context.GetAnimalListForPriceList() };
return View(viewModel);
}
[CompressionFilter(Order = 1)]
[CacheFilter(Duration = 120, Order = 2)]
public virtual ActionResult List(string animal)
{
GodsCreationTaxidermyEntities context = new GodsCreationTaxidermyEntities();
var viewModel = new PriceListIndexViewModel() { AnimalPrices = context.GetPriceListByAnimal(animal) };
return View(viewModel);
}
}
The index work fine. Here's Index.aspx
Index.aspx
<div id="main-content" title="AnimalBox" style="float:none;">
<%--<%= Html.DropDownList("AnimalList", Model.Animals, "[Select One]", new { #class = "inputDropDown" })%>--%>
<% Html.DataList(Model.PriceListAnimals).Columns(6).Item(item =>
{
item.Template(galleryImage =>
{%>
<div style="margin-right:45px; line-height:150%;">
<span><%= Html.ActionLink(galleryImage.AnimalName,"List",new { #animal = galleryImage.AnimalName }) %></span>
</div>
<% });
}).Render(); %>
</div>
Now we move on to the listing page
List.aspx
<div class="maintext" id="pricelist">
<h2 class="sectionHeader">:: Gods Creation Taxidermy : PriceList ::</h2>
<% Html.DataList(Model.AnimalPrices).Columns(7).Item(item =>
{
item.Template(galleryImage =>
{%>
<div><%=galleryImage.TypeName %></div>
<%});
}).Render(); %>
<% Html.DataList(Model.AnimalPrices).Columns(7).Item(item2 =>
{
item2.Template(galleryImage =>
{%>
<div><%=galleryImage.MountPrice %></div>
<% });
}).Render(); %>
</div>
Here's a screenshot of how this is beeing displayed
Screenshot
If anyone couod hekp I'd surely be grately.
EDIT: By the way the images arent being stored in a DB, just the path, which makes this even more fonfusing.
This issue is resolved, I have a couple things backwards

jquery.validate lost on ajax replacement and only showing last error

I am using jquery.validate in MVC 2 with MicrosoftMvcJQueryValidation. I have data annotations on my model which is then being translated into jquery validators. I am using a modification to MicrosoftMvcJQueryValidation as outlined by Soe Tun to allow my error messages to appear in a validation summary instead of beside the controls.
When the page loads, everything works as expected. The problem is that I am using ajax forms with replace mode to rewrite the form. When I do this, I lose all of my client side validation.
Validation still happens server side, and the fields that have errors are correctly being given the css classes to change their style. However, only the last error message is being shown in my validation summary.
The controller isn't anything special. If the model is valid, do work, otherwise return the same model back into the view.
Here's a sample of my ajax form
<% using (Ajax.BeginForm("AddCreditCard", "Dashboard",
new { },
new AjaxOptions() {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "quickpay-wrapper",
OnSuccess = "newPaymentSetup",
LoadingElementId = "loading-pane"
}, new { id="new-credit-card-form" })) { %>
Here is the modified javascript.
jQuery.validator.addMethod("regex", function(value, element, params) {
if (this.optional(element)) {
return true;
}
var match = new RegExp(params).exec(value);
return (match && (match.index == 0) && (match[0].length == value.length));
});
// glue
function __MVC_ApplyValidator_Range(object, min, max) {
object["range"] = [min, max];
}
function __MVC_ApplyValidator_RegularExpression(object, pattern) {
object["regex"] = pattern;
}
function __MVC_ApplyValidator_Required(object) {
object["required"] = true;
}
function __MVC_ApplyValidator_StringLength(object, maxLength) {
object["maxlength"] = maxLength;
}
function __MVC_ApplyValidator_Unknown(object, validationType, validationParameters) {
object[validationType] = validationParameters;
}
function __MVC_CreateFieldToValidationMessageMapping(validationFields) {
var mapping = {};
for (var i = 0; i < validationFields.length; i++) {
var thisField = validationFields[i];
mapping[thisField.FieldName] = "#" + thisField.ValidationMessageId;
}
return mapping;
}
function __MVC_CreateErrorMessagesObject(validationFields) {
var messagesObj = {};
for (var i = 0; i < validationFields.length; i++) {
var thisField = validationFields[i];
var thisFieldMessages = {};
messagesObj[thisField.FieldName] = thisFieldMessages;
var validationRules = thisField.ValidationRules;
for (var j = 0; j < validationRules.length; j++) {
var thisRule = validationRules[j];
if (thisRule.ErrorMessage) {
var jQueryValidationType = thisRule.ValidationType;
switch (thisRule.ValidationType) {
case "regularExpression":
jQueryValidationType = "regex";
break;
case "stringLength":
jQueryValidationType = "maxlength";
break;
}
thisFieldMessages[jQueryValidationType] = thisRule.ErrorMessage;
}
}
}
return messagesObj;
}
function __MVC_CreateRulesForField(validationField) {
var validationRules = validationField.ValidationRules;
// hook each rule into jquery
var rulesObj = {};
for (var i = 0; i < validationRules.length; i++) {
var thisRule = validationRules[i];
switch (thisRule.ValidationType) {
case "range":
__MVC_ApplyValidator_Range(rulesObj,
thisRule.ValidationParameters["minimum"], thisRule.ValidationParameters["maximum"]);
break;
case "regularExpression":
__MVC_ApplyValidator_RegularExpression(rulesObj,
thisRule.ValidationParameters["pattern"]);
break;
case "required":
var fieldName = validationField.FieldName.replace(".", "_");
if ($("#" + fieldName).get(0).type !== 'checkbox') {
// only apply required if the input control is NOT a checkbox.
__MVC_ApplyValidator_Required(rulesObj);
}
break;
case "stringLength":
__MVC_ApplyValidator_StringLength(rulesObj,
thisRule.ValidationParameters["maximumLength"]);
break;
default:
__MVC_ApplyValidator_Unknown(rulesObj,
thisRule.ValidationType, thisRule.ValidationParameters);
break;
}
}
return rulesObj;
}
function __MVC_CreateValidationOptions(validationFields) {
var rulesObj = {};
for (var i = 0; i < validationFields.length; i++) {
var validationField = validationFields[i];
var fieldName = validationField.FieldName;
rulesObj[fieldName] = __MVC_CreateRulesForField(validationField);
}
return rulesObj;
}
function __MVC_EnableClientValidation(validationContext) {
// this represents the form containing elements to be validated
var theForm = $("#" + validationContext.FormId);
var fields = validationContext.Fields;
var rulesObj = __MVC_CreateValidationOptions(fields);
var fieldToMessageMappings = __MVC_CreateFieldToValidationMessageMapping(fields);
var errorMessagesObj = __MVC_CreateErrorMessagesObject(fields);
var options = {
errorClass: "input-validation-error",
errorElement: "span",
errorPlacement: function(error, element) {
var messageSpan = fieldToMessageMappings[element.attr("name")];
$(messageSpan).empty();
$(messageSpan).removeClass("field-validation-valid");
$(messageSpan).addClass("field-validation-error");
error.removeClass("input-validation-error");
error.attr("_for_validation_message", messageSpan);
error.appendTo(messageSpan);
},
messages: errorMessagesObj,
rules: rulesObj,
success: function(label) {
var messageSpan = $(label.attr("_for_validation_message"));
$(messageSpan).empty();
$(messageSpan).addClass("field-validation-valid");
$(messageSpan).removeClass("field-validation-error");
}
};
var validationSummaryId = validationContext.ValidationSummaryId;
if (validationSummaryId) {
// insert an empty <ul> into the validation summary <div> tag (as necessary)
$("<ul />").appendTo($("#" + validationSummaryId + ":not(:has(ul:first))"));
options = {
errorContainer: "#" + validationSummaryId,
errorLabelContainer: "#" + validationSummaryId + " ul:first",
wrapper: "li",
showErrors: function(errorMap, errorList) {
var errContainer = $(this.settings.errorContainer);
var errLabelContainer = $("ul:first", errContainer);
// Add error CSS class to user-input controls with errors
for (var i = 0; this.errorList[i]; i++) {
var element = this.errorList[i].element;
var messageSpan = $(fieldToMessageMappings[element.name]);
var msgSpanHtml = messageSpan.html();
if (!msgSpanHtml || msgSpanHtml.length == 0) {
// Don't override the existing Validation Message.
// Only if it is empty, set it to an asterisk.
//messageSpan.html("*");
}
messageSpan.removeClass("field-validation-valid").addClass("field-validation-error");
$("#" + element.id).addClass("input-validation-error");
}
for (var i = 0; this.successList[i]; i++) {
// Remove error CSS class from user-input controls with zero validation errors
var element = this.successList[i];
var messageSpan = fieldToMessageMappings[element.name];
$(messageSpan).addClass("field-validation-valid").removeClass("field-validation-error");
$("#" + element.id).removeClass("input-validation-error");
}
if (this.numberOfInvalids() > 0) {
errContainer.removeClass("validation-summary-valid").addClass("validation-summary-errors");
}
this.defaultShowErrors();
// when server-side errors still exist in the Validation Summary, don't hide it
var totalErrorCount = errLabelContainer.children("li:not(:has(label))").length + this.numberOfInvalids();
if (totalErrorCount > 0) {
$(this.settings.errorContainer).css("display", "block").addClass("validation-summary-errors").removeClass("validation-summary-valid");
$(this.settings.errorLabelContainer).css("display", "block");
}
},
messages: errorMessagesObj,
rules: rulesObj
};
}
// register callbacks with our AJAX system
var formElement = document.getElementById(validationContext.FormId);
var registeredValidatorCallbacks = formElement.validationCallbacks;
if (!registeredValidatorCallbacks) {
registeredValidatorCallbacks = [];
formElement.validationCallbacks = registeredValidatorCallbacks;
}
registeredValidatorCallbacks.push(function() {
theForm.validate();
return theForm.valid();
});
theForm.validate(options);
}
// need to wait for the document to signal that it is ready
$(document).ready(function() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
});
I've tried moving the calls at the bottom in the document ready into my OnSuccess method, but that didn't do it.
So, how do I get client side validation to reinitialize when I do my ajax replace, and how do I get all my errors to show in the validation summary? I'm hoping that if I fix one issue, it will correct the other.
EDIT:
Here's a little more info about what I am doing
Here's the wrapper
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<QuickPayModel>" %>
<div id="quickpay-wrapper">
<% if (Model.NewPaymentMethod) { %>
<% Html.RenderAction<DashboardController>(x => x.QuickPayNewMethod()); %>
<% } else { %>
<% Html.RenderPartial("QuickPayMakePayment", Model); %>
<% } %>
</div>
Here is the make a payment panel.
<%= Html.ClientValidationSummary(new { id = "valSumContainer" })%>
<% Html.EnableClientValidation(); %>
<% using (Ajax.BeginForm("QuickPay", "Dashboard",
new { },
new AjaxOptions() {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "quickpay-wrapper",
OnSuccess = "updatePaymentHistory",
LoadingElementId = "loading-pane"
}, new { }))
{ %>
<div class="horizontalline"><%= Html.Spacer() %></div>
<% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>
<p>
<%: Html.LabelFor(x => x.PaymentMethods)%>
<% if (Model.HasOnePaymentMethod) { %>
<%: Html.DisplayFor(x => x.SelectedPaymentMethodName) %>
<%: Html.HiddenFor(x => x.SelectedPaymentMethodId) %>
<% } else { %>
<%: Html.DropDownListFor(x => x.SelectedPaymentMethodId, Model.PaymentMethodsSelectList, "Select a Payment Method", new { })%>
<%: Html.HiddenFor(x => x.SelectedPaymentMethodName)%>
<script type="text/javascript">
$(function () {
$("#PaymentMethods").change(function () {
$("#SelectedPaymentMethodId").val($(this).val());
$("#SelectedPaymentMethodName").val($('option:selected', this).text());
});
});
</script>
<% } %>
<%: Html.Spacer(12, 1) %><%: Ajax.ActionLink("New Payment Method", "QuickPayNewMethod",
new AjaxOptions() { InsertionMode = InsertionMode.Replace,
UpdateTargetId = "quickpay-wrapper",
OnSuccess = "newPaymentSetup",
LoadingElementId = "loading-pane"
})%>
<%: Html.ValidationMessageFor(x => x.SelectedPaymentMethodId)%>
</p>
<p>
<%: Html.LabelFor(x => x.Amount)%>
<%: Html.TextBoxFor(x => x.Amount, new { disabled = Model.UseInvoicing ? "disabled" : String.Empty,
title = Model.UseInvoicing ? "the total payment amount of all selected invoices" : String.Empty,
#class = "small" })%>
<%: Html.ValidationMessageFor(x => x.Amount)%>
</p>
<p>
<%: Html.LabelFor(x => x.PayDate)%>
<%: Html.TextBox("PayDate", Model.PayDate.ToShortDateString(), new { #class = "medium" })%>
<%: Html.ValidationMessageFor(x => x.PayDate)%>
</p>
<script type="text/javascript">
$(function () {
quickPaySetup();
});
</script>
<div class="horizontalline"><%= Html.Spacer() %></div>
<%= FTNI.Controls.Submit("Submit Payment") %>
<%: Html.AntiForgeryToken() %>
<%: Html.ValidationMessage("Payment-Result")%>
<% } %>
And now my new payment method panel
<script type="text/javascript">
$(function () {
newPaymentSetup();
});
</script>
<h4>New Payment Method</h4>
<% if(Model.HasPaymentMethods) { %>
<span style="float:right;">
<%: Ajax.ActionLink("Cancel", "QuickPay",
new AjaxOptions() {
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "quickpay-wrapper",
OnSuccess = "quickPaySetup",
LoadingElementId = "loading-pane"
})%>
</span>
<% } %>
<div>Enter the information below to create a new payment method.</div><br />
<%= Html.ClientValidationSummary(new { id = "valSumContainer" })%>
<% Html.EnableClientValidation(); %>
<div id="new-payment-method-tabs">
<ul>
<li>Credit Card</li>
<li>E-Check</li>
</ul>
<div id="new-credit-card">
<% Html.RenderPartial("NewCreditCard", Model.CreditCardModel); %>
</div>
<div id="new-ach">
<% Html.RenderPartial("NewACH", Model.ACHModel); %>
</div>
</div>
Each form starts off with something like this
<% using (Ajax.BeginForm("AddCreditCard", "Dashboard",
new { },
new AjaxOptions() {
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "quickpay-wrapper",
OnSuccess = "newPaymentSetup",
LoadingElementId = "loading-pane"
}, new { id="new-credit-card-form" })) { %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>
Initial load works. Any ajax replaces cause the form context to be lost and not reinitialize no matter what I do. The form posts back, validation occurs server side. All invalid fields are changed (css error classes added), but only the last error is shown in the summary.
I am going to tell you how I did just a few days ago. Please have a look to this question for details.
In my case I was showing the content of the form using an ajax call inside a jquery dialog. When the call complete I just replace the dialog content with the content sent back from the controller.
I have modified the code inside the Microsoft script as described in my question and then called the init method on document ready. This should work for your case too...
For the second error (how do I get all my errors to show in the validation summary?) I have simply modified the code as described in the same source post you are referring to and did not experienced any problem.
Hope it helps!
I ended up reworking my solution so that I was no longer writing the forms to the page through callbacks. While this was not my intended approach, it does work. I chose to use jquery modals to display the data rather than changing the content of one area of the screen.
Ideally, I would not have to render all of the forms to the page and could call them up on demand, but it seems jquery client side validation will not wire up unless the form is present on the page load. I am unsure of the form elements are required present on form load, but it may be a limitation I just have to deal with.
Another workaround would have been to render them all to the page and just show/hide each form through jquery. It's not much different than using modals, but at least the validation would work. I'd still like to see a solution where forms using validation summaries and client side jquery validation through data annotations can be written to the page through callbacks and still wired up and function correctly.

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

How can i Set RadioButtonFor() as Checked By Default
<%=Html.RadioButtonFor(m => m.Gender,"Male")%>
there is way out for (Html.RadioButton) but not for (Html.RadioButtonFor)
any Ideas?
Use the simple way:
<%= Html.RadioButtonFor(m => m.Gender, "Male", new { Checked = "checked" })%>
It's not too pretty, but if you have to implement only very few radio buttons for the entire site, something like this might also be an option:
<%=Html.RadioButtonFor(m => m.Gender,"Male",Model.Gender=="Male" ? new { #checked = "checked" } : null)%>
I assume you should have a group of radio buttons. something could be like
<%=Html.RadioButtonFor(m => m.Gender,"Male")%>
<%=Html.RadioButtonFor(m => m.Gender,"Female")%>
<%=Html.RadioButtonFor(m => m.Gender,"Unknown")%>
You may give the default value for m.Gender = "Unknown" (or something) from your controller.
This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.
This Helper evaluates the expression and if equals to the value it checks the radio button, and has the same parameters than RadioButtonFor (for this reason the name is diferent):
public static MvcHtmlString CheckedRadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value)
{
return CheckedRadioButtonFor(htmlHelper, expression, value, null);
}
public static MvcHtmlString CheckedRadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
{
var func = expression.Compile();
var attributes = new RouteValueDictionary(htmlAttributes);
if ((object)func(htmlHelper.ViewData.Model) == value) {
attributes["checked"] = "checked";
}
return htmlHelper.RadioButtonFor(expression, value, attributes);
}
Usage:
<%= Html.CheckedRadioButtonFor(m => m.Gender, "Male", new { id = "gender-male" })%>
Result:
<!-- For Model.Gender = "Male" -->
<input checked="checked" id="gender-male" name="Gender" type="radio" value="Male">
<!-- For Model.Gender = "Female" -->
<input id="gender-male" name="Gender" type="radio" value="Male">
I found another option so you can just use #Html.EditorFor() with templates:
Say I have this enum:
public enum EmailType { Pdf, Html }
I can put this code in Views/Shared/EditorTemplates/EmailType.cshtml
#model EmailType
#{
var htmlOptions = Model == EmailType.Html ? new { #checked = "checked" } : null;
var pdfOptions = Model == EmailType.Pdf ? new { #checked = "checked" } : null;
}
#Html.RadioButtonFor(x => x, EmailType.Html, htmlOptions) #EmailType.Html.ToString()
#Html.RadioButtonFor(x => x, EmailType.Pdf, pdfOptions) #EmailType.Pdf.ToString()
Now I can simply use this if I want to use it at any time:
#Html.EditorFor(x => x.EmailType)
It's much more universal this way, and easier to change I feel.
Came across this and thought I would point out that for MVC 5 all you need to do is set the value on the model. For Example:
Model:
public class ExampleModel
{
public PackingListInputModel()
{
RadioButtonField = "One";
}
public string RadioButtonField { get; set; }
}
View :
#model ExampleModel
#using (Html.BeginForm)
{
#Html.RadioButtonFor(m => m.RadioButtonField , "One")
#Html.RadioButtonFor(m => m.RadioButtonField , "Two")
}
The state of the first radio button ("One") will be set as active because the value matches what was set in the model.
You can also add labels that are tied to your radio buttons with the same ID, which then allows the user to click the radio button or label to select that item. I'm using constants here for "Male", "Female" and "Unknown", but obviously these could be strings in your model.
<%: Html.RadioButtonFor(m => m.Gender, "Male",
new Dictionary<string, object> { { "checked", "checked" }, { "id", "Male" } }) %>
<%: Html.Label("Male") %>
<%: Html.RadioButtonFor(m => m.Gender, "Female",
new Dictionary<string, object> { { "id", "Female" } }) %>
<%: Html.Label("Female")%>
<%: Html.RadioButtonFor(m => m.Gender, "Unknown",
new Dictionary<string, object> { { "id", "Unknown" } }) %>
<%: Html.Label("Unknown")%>
<%: Html.RadioButtonFor(m => m.Gender, "Male", new { #checked = true } )%>
or
#checked = checked
if you like
If you're using jquery, you can call this right before your radio buttons.
$('input:radio:first').attr('checked', true);
^ This will check the first radio box, but you can look at more jquery to cycle through to the one you want selected.
#Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
#Web.Mvc.Claims.Resources.PartyResource.MaleLabel
#Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
#Web.Mvc.Claims.Resources.PartyResource.FemaleLabel
Here is code to set default radio button set to true
#Html.RadioButtonFor(m => m.Gender, "Male", new { #checked = "checked", id = "rdGender", name = "rbGender" })
I find it best to just put the default value in the constructor method of the model.
Gender = "Male";
You need to add 'checked' htmlAttribute in RadioButtonFor, if the radiobutton's value matches with Model.Gender value.
#{
foreach (var item in Model.GenderList)
{
<div class="btn-group" role="group">
<label class="btn btn-default">
#Html.RadioButtonFor(m => m.Gender, item.Key, (int)Model.Gender==item.Key ? new { #checked = "checked" } : null)
#item.Value
</label>
</div>
}
}
For complete code see below link: To render bootstrap radio button group with default checked.
stackoverflow answer link