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>
Related
I have A button of BtnNext() that when click will Dequeue the items the I Enqueue. I use Tempdata so that I can use the Dequeued data and render it on my view.
Here is the controller:
public ActionResult BtnNext()
{
var first = MyQueue.todayQueue.Dequeue();
MyQueue.todayQueue.Count();
TempData["QueueItem"] = first;
return View();
}
Here is my view:
#Html.ActionLink(" ", "BtnNext", null, new { #class = #cssClass, #id = "Link1" })
I expect this button to behave like this.
When I click this button it will refresh the page and render the Dequeued data in the same view just change A portion of my view with the dequeued property
Right now what this code is doing when I click the BtnNext() the error is its trying to find A view with url like this http://localhost:50000/TellerScreens/BtnNext but I don't want it to go to another page, I just want to update a portion of the Index so the url must stay
http://localhost:50000/TellerScreens
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>
I have a form where a user fils in some details, and submits the data with a submit button.
I need to add a new button to my form, which does a post back, passing the model back, adds some items to a List<> (which is a property of the model), and then refreshes the page.
How do I route the post to a different action than the form's post method?
You can use the name of the submit button as a parameter in your action.
Let's say you have the following submit buttons:
<input type="submit" name="btnCompare" value="Compare" />
<input type="submit" name="btnSave" value="Save" />
You can capture both of them in one action and then check to see which one was clicked:
[HttpPost]
public ActionResult SavedResults(Results myResults, string btnCompare, string btnSave) {
if (btnCompare != null) {
//btnCompare was clicked. Do related stuff here.
}
else if (btnSave != null) {
//btnSave was clicked. Do related stuff here.
}
}
you should use two different buttons with same name but different value and use this button name in your post action on controller with condition.
use this in your view
use following code on controller.
[HttpPost]
public ActionResult ActionName(ModelName model, string Action)
{
if(Action.Equals("button1")
{
}
if(Action.Equals("buttons")
{
//write your code to add items in list
model.itemList.Add(newitem);
}
return RedirectToAction("ActionName",model);
}
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.
On an app I'm working on, I have a requirement that, upon clicking a certain button, validation fires on some related textboxes; if they do not pass, nothing occurs, otherwise an action that is fired from an AJAX call occurs. This AJAX call returns some message about the success of the operation.
My partial view this is occurring in looks a bit like this:
<div>
<div id='cell-phone'>
#Model.ValidationMessageFor(x=>x.Model.CellNumber)
#Model.TextBoxFor(x=>x.Model.CellNumber)
</div>
<div id='pager'>
<!-- Ditto, only x.Model.Pager; yes, some people use pagers still. -->
</div>
<div id='page-address'>
<!-- ... x.Model.PageAddress ... -->
</div>
<div id='pager-test'>
<a href='#' id='test-pager' class='button'>Test</a>
<span id='test-result'></span>
</div>
</div>
<script>
var $cellNum = $('#cell-phone input'),
$pagerNum = $('#pager input'),
$pageAddress = $('#page-address input'),
$testPager = $('#pager-test'),
$testResult = $('#test-result');
$(document).ready(function () {
$testPager.click(function () {
pagerTest();
});
});
function pagerTest() {
var args = { address: $pageAddress.val() };
$.getJSON('#Url.Action("SendTestPage")', args, function(result) {
$testResult.html(result.Message);
});
}
</script>
...down at the server level...
public JsonResult SendTestPage(string address)
{
// SNIP: Other unnecessary details.
var result = new EmailSendResult
{
success = SendEmailMethod(address)
};
result.message = result.success
? "Message sent!"
: "Couldn't send message...";
return result;
}
....
public class EmailSendResult
{
public bool success;
public string message;
}
Question: while I am able to get the message/success values back, I also need to cause the View Model's validations to fire. I don't see how to do this using an AJAX call. My suspicion is that either A) I'm using the wrong tool for the job, or B) I'm using the right tool for one job, but I need something else. What am I missing to be able to cause validations to fire?
When you click on 'test-pager' link, the action will be called but the validation of your form doesn't trigger because your link is not a submit. If you want to validation work you must have a submit button on the form. When the user clicks it the validation will fire. So change the test-pager to something like this:
<input type="submit" id="test-pager" class="button" />
Or ( if I understand question correctly) you can bind address textbox change event and within it call testPage function.