Show/Hide sections based on radio button selection - c#

I'm working on a ASP.NET MVC 4 web application. I have a view where some sections should be shown/hidden based on the selection of a radio button list (3 radio buttons A), B) , C). )
It seems there is no way to do this without using jquery/javascript ?
According this post:
Postback on RadioButtonFor in MVC
"There is no server side event occurring when the user changes the selection of a radio button."
Can I perform a postback with my radio buttons and show/hide sections based on the selection?
Please, let me know if it can be done without javascript and just pure ASP.NET MVC 4+ code.

Here is the controller code:
[HttpPost]
public ActionResult SaveIndex()
{
return View();
}
Here is the code for view:
<div>
#using (Ajax.BeginForm("SaveIndex", "Home", new AjaxOptions { HttpMethod = "Post"}, new { id = "MainForm" }))
{
#Html.RadioButton("My Radio1", "Radio1", new { onchange = "this.form.submit();" })
#Html.RadioButton("My Radio2", "Radio2", new { onchange = "this.form.submit();" })
}
</div>

Related

view not reaching controller

this simple mvc app wants a radio button, text input works but radio button not giving me a return, for example, theres 3 buttons (red, blue, green) and if I choose 'red' then viewbag.sup is going to return 'red chosen!' but even though I run this and check 'red' nothing happens, here's what I got:
View (Search.cshtml):
#using (Html.BeginForm("Search", "Home", FormMethod.Post))
{
#Html.RadioButton("color", "red", new { id = "isRed" })
#Html.RadioButton("color", "blue", true)
#Html.RadioButton("color", "green")
}
<p>#ViewBag.Sup</p>
Controller (HomeController.cs):
public ActionResult Search(string color)
{
if (color == "red")
{
ViewBag.Sup = "red chosen!";
}
return View("Search");
}
this looks good right? what am I doing wrong?
You need a mechanism to actually submit the form. For example you could add a button to do that within the form:
<button type="submit"/>
Alternatively add a change event handler to the radio buttons that will submit the form (I've used JQuery here, which you almost certainly have loaded if you've used a standard MVC project template, although there are various other ways to attach such a handler to the radio button elements):
#using (Html.BeginForm("Search", "Home", FormMethod.Get, new { id = "SearchForm" }))
...
<script type="text/javascript">
$('input[type=radio]').on('change', function() {
$("#SearchForm").submit();
});
</script>

Validation Message Not Displays On ModelState.IsValid

I am developing my first application using Asp.Net MVC5. In my application I have single view,In which I am going to call two action. One action by using button and another by actionlink. When I call it using button it works perfectly for validation messages.
In other hand , If I click on 'Add Another'(which is action link) I want same validation, But It does not showing any validation messages. I have implemented below code for #Html.ActionLink() click event.
In Razor View -
#Html.ActionLink("Add Another", "AddNew", "AgreementRegistration", new { #class = "postLink" })
In Controller -
[HttpPost]
public ActionResult AddNew(User_Master usermaster, Commercial_Master commercialmaster, Property_Master propertymaster, PropertyCommercial_Master propertycommercialmaster, PropertyDetails_Master propertydetailsmaster, SecurityDeposit_Master securitydepositmaster, PropertyUser_Master propertyusermaster, UserType_Master usertypemaster)
{
agreementnew = new AgreementNew(usermaster, commercialmaster, propertymaster, propertycommercialmaster, propertydetailsmaster, securitydepositmaster, propertyusermaster, usertypemaster);
if (ModelState.IsValid)
{
//Some Logic
return View("InitialView", agreementnew);
}
else
{
//Some Logic
return View("InitialView", agreementnew);
}
}
When I checked it using debugger then it comes to above method in else block but does not showing any validation message. I want to display all the validation message when I click on ActionLink. How do I solve this problem?
by clicking on action link it doesn't submit your form. Validation is only checked when your form is submitted. So use Javascript to submit your form when clicking on your action link.
First change your action link to this.
#Html.ActionLink("Add Another", "AddNew", "AgreementRegistration", new { #class = "postLink", onclick="submitMyForm()" })
Then add following code
<script>
function submitMyForm(){
$("#yourFormID").submit(); //assign an id to your form and use that here
}
</script>

How to conditionally include page elements in form tag

Working in C#, Visual Studio 2012, MVC4 EF.
I have a view that, when a condition is met, I want to be a form. How do I do this without having to have one section with the page elements in a form, and another section with the same page elements not in a form?
Here is my code for the condition:
#if (this.Model.ItemRequestStatusId == Portal.BusinessModel.Entities.ItemRequestStatusId.VendorRepReview
&& this.User.IsInRole("Vendor Rep"))
{
using (Html.BeginForm("Edit", "ItemRequest", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<button id="btn-data-integrity-final-review" class="btn btn-warning pull-right" type="submit">Vendor Review Complete</button>
}
}
else
{
#Html.ActionLink("Edit this request", "Edit", new { id = this.Model.Id }, new { #class = "btn btn-default pull-right" })
}
and then below that condition, I have the page elements/fields. But they currently don't fall within the form (only the submit button is within the form). I want to capture the fields in POST.
The only way to achieve that is to use javascript. For example you could subscribe to the submit event of this form and then clone all the fields into the form before submitting:
$('#formId').submit(function() {
var inputFields = $('#someDivContainingYourInputFields').clone();
$(this).append(inputFields);
});
But a better approach would be to simply organize your markup in such a way that the input fields are inside the form. You could achieve that by moving the form definition outside of the condition and wrap the input fields with it. Only the submit button could stay inside the if.

Need help to finish async form post and screen update using jquery

I'm pretty much a jquery newb...I've almost got this working I think, let me know if i can clarify anything.
I have a screen displaying a list..let's call them affiliates. To create a new affiliate, a modal style pop up dialogue is used.
When the dialogue "Create" button is clicked, the form data must be saved (creating a new affiliate), the dialogue disappears, and the affiliate list updates without reloading the page
The jquery file at the bottom shows how I'm trying to do it now: trying to detect a click on the "confirm" button, get the form to submit using the data target property, and using the form's target property to know what container to update.
What is happening is: nothing. The cancel button works, create button does absolutely nothing.
Also note that the "Create" button, which will act as the form's submit, is not located within the <form> tags.
I'm pretty sure I'm doing modals wrong but let's ignore that for the moment and focus on the async post and list update. I've included my relevant code below to support my post.
--AffiliateListPartial
#model IPagedList<Acme.Business.DomainModel.Affiliates.Affiliate>
<div class="items-list" id="affiliate-list-view">
#foreach (var item in Model)
{
<a href="#Url.Action("AffiliateDetails", "Vendor", new { id = item.AffiliateId })">
//basic spans and razor display list in here..nothing notable
</a>
}
</div>
The above partial view is contained within a full view, lets call it AffiliateList. Nothing particularly relevant in there except that it is controlled by the VendorController/Affiliatelist method.
The VendorController.AffiliateList looks like:
public ActionResult AffiliateList(string searchTerm = null, int page = 1)
{
var userId = WebSecurity.GetUserId(User.Identity.Name);
var model = (from a in db.Affiliates.ToList()
where a.VendorId == userId
select a).ToPagedList(page, 15);
if(Request.IsAjaxRequest()) return PartialView("_AffiliateListPartial", model);
return View(model);
}
The modal style dialoque for creating a new affiliate (I'll just include the lines that I think are relevant):
_Modal.AffiliateCreate.Partial
<form id="affiliate-create-form" class="form" method="post" action="#Url.Action("AffiliateCreate")" data-acme-ajax="true" data-acme-target="#affiliate-list-view">
// multiple input elements
</form>
<div class="modal-footer">
<button name="close_modal"><span>Cancel</span></button>
<button name="confirm" data-acme-target="#affiliate-create-form"><span>Create</span></button>
</div>
And the VendorController.AffiliateCreate method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AffiliateCreate(Affiliate affiliate)
{
if (!ModelState.IsValid) return View(affiliate);
db.Affiliates.Add(affiliate);
db.SaveChanges();
return RedirectToAction("AffiliateList");
}
And the .js file's relevant parts:
$("button[name='confirm']").on("click", function() {
var $form = $(this).attr("data-acme-target");
var options = {
url: $form.attr("action"),
type: $form.attr("type"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-acme-target"));
var $newHtml = $(data);
$target.replaceWith(data);
$newHtml.effect("highlight");
});
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
$("button[name='close_modal']").on("click", function(event) {
$(".modal_overlay").css("opacity", "0");
$(".modal_container").css("display", "none");
return false;
});
var $form = $(this).attr("data-acme-target"); is getting the attribute named 'data-acme-target' of the button, rather than the form it's associated with. So then when you're using $form.attr('action'), you aren't getting anything back.
Since data-acme-target is an ID to another control that is the form you want to submit, use $($(this).attr("data-acme-target")); to get it.

Custom validation attribute is not working for button click

I have created a function for doing on validations on textbox entered value based on selection in drop downlist .. ..suppose If the dropdownlist selected item is amount then the entered value in textbox must be in between 10 t0 20 like this i have got two more validations.. for that purpose, I have got one textbox and one dropdwonlist and one button in my view
when i enter value in textbox as 30 and select the drop downlist item as "Amount" and then click on the submit button, the view is not showing any error message and ( if i left textbox as empty and then press submit button its should show error msg but its not showing) (I have written Custom functions for validating these ones on server side)
I have put a breakpoint at a postValues method but its not hitting ...
for that I have done like this (controller part)
public class CrossFieldsTxtboxesController : Controller
{
public ActionResult Index()
{
var itemsforDropdown = new List<SelectListItem> {
new SelectListItem{ Text = "Amount" , Value = "Amount"},
new SelectListItem{Text= "Pound", Value ="Pound"},
new SelectListItem {Text ="Percent", Value ="percent"}
};
ViewData["Listitems"] = itemsforDropdown;
return View("DdlCrossFields");
}
[HttpPost]
public ActionResult PostValues(CrossFieldValidation model)
{
if (!ModelState.IsValid)
{
return View(model);
}
else
{
return RedirectToAction("DdlCrossFields");
}
}
}
and this is my view part
#model MvcSampleApplication.Models.CrossFieldValidation
#{
ViewBag.Title = "DdlCrossFields";
}
<h2>DdlCrossFields</h2>
#using (Html.BeginForm())
{
<div class ="editor-field">
#Html.TextBoxFor(m => m.TxtCrossField)
#Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
#Html.DropDownList("Listitems",ViewData["Listitems"] as SelectList)
<input id="PostValues" type="Submit" value="PostValues" />
}
and this is my model part
public class CrossFieldValidation
{
public string DDlList1
{ get; set; }
[Required(ErrorMessage = "Quantity is required")]
[Display(Name= "Quantity:")]
[ValueMustbeInRange]
[NumericAttributes]
public string TxtCrossField
{ get; set; }
}
would any one have any idea why its not working for button click , any suggestions also would be grateful
many thanks..
I don't see any place where you specify an action that should handle POST request (PostValues in your case). You can use an overload of Html.BeginForm and specify POST action name explicitly:
Html.BeginForm("PostValues", "CrossFieldsTxtboxes")
If I'm right, your POST requests go to Index action and therefore ModelState.IsValid is not checked there.
You can use client side validation using jQuery Unobtrusive validation plugin. Please check if you have the following keys in your web.config file:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
But note that custom validation attributes require additional JavaScript code to work on client.
I dont see where you are actually calling the method when you do the post - do you have a javscript click handler?
You need to have the method and controller you want to go to in your Html.BeginForm() or you can have something like the below in your view:
#Html.ActionLink("Post Values", "PostValues", "CrossFieldsTxtboxesController", null, new { #class = "postValuesButton", onclick = "return false;" })

Categories

Resources