two submit buttons on a form - asp.net-mvc

lets say I have a set of establishments, each establishments know who his father is and a establishment can have many childs. now I created a set of cascading dropdowns for this problem so on the first whe find the ones that have no father ( tier 0 if you might), once the user selects an item the list on the second list its children are loaded ( if it has any children) and so on until tier 3, heres my code:
Index.cshtml:
#model WebUI.Controllers.IndexViewModel
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#Html.Partial("ParentEstablishments",Model)
<div id="FirstHeritage">#Html.Partial("FirstHeritageChildren",Model)</div>
<div id="SecondHeritage">#Html.Partial("SecondHeritageChildren",Model)</div>
Each partial view has an ajax form like the following:
#model WebUI.Controllers.IndexViewModel
#using (Ajax.BeginForm("SelectParent","Ticket",new AjaxOptions{UpdateTargetId="FirstHeritage"}))
{
<fieldset>
<legend>Entidad departamental</legend>
#Html.DropDownListFor(
m => m.SelectedParentId ,
new SelectList( Model.AvailableParents , "EstablishmentId" , "Name" ) ,
"[Por favor seleccione una entidad departamental]"
)
<input type="submit" value="Select" />
</fieldset>
}
so what i want to create is a submit button that lets the user tell me hes selected the entity he needs and to call a method on my controller where i check every id for a value, i tried to put the partial views inside a form but every submit button of the ajax forms calls the method of the form i create, how can i make a button without interfering with the ajax forms?

Modify the Button like below.
<input type="button" value="Select" class="btnSubmit" />
Mofify the Form Tag as mentioned below
#using (Ajax.BeginForm("SelectParent","Ticket", FormMethod.Post,
new { id = "myForm" }))
{
}
Modify the Div as mentioned below. Add an attribute which will have value corresponding to it's Controller's Action method.
<div id="FirstHeritage" attr-Url="#Url.Action("ActionName", "ControllerName",
new { area = "AreaName" })"></div>
Now in Jquery. Follow below steps.
Load Partial View
Fetch the Div Attribute Value
Use On for the Button event.
Ajax Request
JQuery
$(document).ready(function () {
var FirstHeritage = $('#FirstHeritage');
var url = FirstHeritage.attr('attr-Url');
FirstHeritage.load(url, function () {
var $form = $('#myForm');
$.validator.unobtrusive.parse($form);
$(document).on('click', '.btnSubmit', function () {
if ($form.valid()) {
$.ajax({
url: Url,
async: true,
type: 'POST',
beforeSend: function (xhr, opts) {
},
contentType: 'application/json; charset=utf-8',
complete: function () { },
success: function (data) {
$form.html(data);
$form.removeData('validator');
$form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($form);
}
});
}
});
});
});
Hope this will help you.

You can't, essentially. The script that makes the AJAX form an AJAX form binds to the submit event, so any submit will be caught.
Remember all the HTML helpers and controls in ASP.NET are there to cover common scenarios and make your life easier when you're actually in a common scenario. The more "custom" your code gets (such as a second submit button that will do a regular POST instead of an AJAX POST), the more work you need to do (and the less you should be using the builtin helpers and controls).
Just create a regular form (Html.BeginForm), add your two submit buttons, and then attach a click event on the AJAX version, and then send the POST as AJAX yourself.

Related

Second time partialview not loading to div via from .ajax() in MVC4

I have issue loading partialview to div second time. I have checked previous posts in SO but non of them really helped me. So I am posting my issue here.
index.cshtml
<div id="DivEmailContainer" style="display:block" class="row">
</div>
_EditEmail.cshtml
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-2 ">
<input type="submit" value="Save" class="btn btn-success width100per" />
</div>
script type="text/javascript">
$(function () {
$("#frmEmail").validate({
rules: {
...
submitHandler: function (form) {
$.ajax({
url: 'PostEditEmail',
type: 'Post',
data: $(form).serialize(),
success: function (result) {
alert("In success");
$('#DivEmailContainer').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
},
complete: function (xhr, textStatus) {
alert(xhr.responseText);
alert(textStatus);
}
});
}
});
controller
public PartialViewResult PostEditEmail(string actiontype, FormCollection col)
{
var communicationLocation = string.Empty;
....
return PartialView("_EditEmail", memberemail);
}
First time partialview loading into DivEmailContainer to error. If submit again partialview loading full post back. not even it is calling submitHandler.
Only thing I observed is 1st time submit <form post was /ContactInformation/GetEditEmailbut when I submit second time <form post was /ContactInformation/PostEditEmail.
What could be wrong?
update
second time Forloop scriptblock loading. May be it is issue with Forloop?
#using (Html.BeginScriptContext())
{
Html.AddScriptBlock(
update
issue with forloop htmlhelper, not with ajax. secondtime script is not loading. #Russ Cam can help on this.
from my experience putting script in a partial leads to very inconsistent results. expecially with the script being inserted into the middle of the page. I would highly recommend that you pull your script from the partial and put it on the main page. Since the partial is loaded after the page load you will need to tie the script to the partial one of 2 ways.
1. tie the events to the document
$(document).on('click', '.targetClass', function(){
//do stuff
});
for example to put an id on your input and change it to a button
<input type="button" value="Save" id="btnSave" class="btn btn-success width100per" />
your click event would then be
$(document).on('click', '#btnSave', function(){
//your ajax call here
});
being tied to the document this click event would fire even though the input is inserted into the document after load
put the script in a function that is called after the partial is loaded
change your
$(function () {
to
function partialScript(){
and call this function after the partial is loaded
$('#DivEmailContainer').html(result);
partialScript();
Try to load partial view like this
$("#DivEmailContainer").load('#Url.Action('ActionName', 'ControllerName')', function () {
//Perform some operation if you want after load.
});

How to render view in same page onclick of link in mvc

i have two views:
Index
Create
Contents of each view:
Index
'Create' link
display records from table in database.
Create
Create new record and save it and back to index view.
I want to display the Create view in the Index view when users click on 'Create' Link. What is the best way to do it?
You may use jQuery load() function. You need to change your Create View to PartalView.
Then on your Index View you need something like that:
Create
<div class="divForCreate"></div>
<script>
$('.Create').click(function() {
$('.divForCreate').Load('#Url.Action("Create", "Home", new {id = Model.id})')
});
</script>
Your demand can also be realized using $.ajax(), which is a little bit complex than simply using load(), but can easily applied when your data come from a different domain. For example,
<input type="submit" value="create" onclick="create();"/>
<div id="bottom_row"></div>
<script>
function create(){
//you can get your paramters like this.
var link_head = $("#link_head").val();
$.ajax({
type : "get",
async:false,
url : "http://yourIP:port/path to method.action?paramters,
dataType : "jsonp",
jsonp: "callbackparam",
jsonpCallback:"success_jsonpCallback",
success : function(json){
if(json.Status){
location.reload();
//your further action here
}else{
alert("Error");
}
},
error:function(){
alert('fail');
}
});
}
</script>

How to make ajax postback in form with list of check boxes

I dynamically draw checkboxes in my form:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="itemsList"}))
{
foreach (var lt in Model.MyList)
{
<li>
<label id="label">
<input value="#lt.itemId" type="checkbox" />
#lt.Title</label>
</li>
}
}
JQuery function:
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
});
...
But my action is not fired. Am I doing something wrong here? I am expecting that when I check checkbox make server call.
I am expecting that when I check checkbox make server call.
You should not expect that unless you've written handler for checkbox change
$(document).ready(function () {
$('#itemsList').ajaxForm({
success: Saved,
error: HandleError
});
$(':checkbox').change(function(){
$('#itemsList').submit();
});
});
ajaxForm will intercept submissions and send them via ajax. But you need to trigger a submit for the ajax call to kick in.
Try adding:
$('input[#type="checkbox"]').click(function(){ $('#itemsList').submit(); }
You may want to refine the checkbox selector to something more specific...

list is not refreshed in mvc 3 view

I have an asp.net view which has two partial views. One for edit information and other one for displaying list of changes that were made. When I hit the update button, the list is not updated. I used ajax.begin form. How can I do this?
Main view has like this:
<div class="accountdetails1">
#Html.Action("UpdateAccountDetails", new { dispute = dispute })
</div>
<div>
list of changes
#Html.Action("GetAccountAudit")
</div>
updateAccountDetails is like this in start:
#using (Ajax.BeginForm("UpdateAccountDetails", new AjaxOptions
{
LoadingElementId = "loading",
LoadingElementDuration = 2000,
OnSuccess = "OnSuccess",
OnBegin = "OnBegin",
}))
{
and functions are like this:
<script type="text/javascript">
function OnSuccess() {
var div = $('#dvMessage');
div.html('');
div.append('Account Information has been updated.');
}
function OnBegin() {
var div = $('#dvMessage');
div.html('');
}
</script>
to show success or failure of update Do I need to update change list in success method? Please suggest
#Ajax methods works in following way:
#Ajax.ActionLink - requests HTML from pointed action via AJAX and puts result in HTML element with id equals to UpdateTargetId value specified in AjaxOptions.
#Ajax.BeginForm - gets the all inputs and selects and other form elements inside using(Ajax.BeginForm()) { .. } and submits it to specified action (using AJAX) then puts response to HTML element with id specified in AjaxOptions.UpdateTargetId property.
So you need something like
<div id="myContainer" >
#using(Ajax.BeginForm("yourActionToProcessEdits", new AjaxOptions { UpdateTargetId = "myContainer" }))
{
.. Form for edit information
#Html.EditorFor(m => m.EditMe)
...
<input type="submit" value="Update" />
.. Display changes here
#Html.Raw(Model.MyChanges)
}
You need to request the GetAccountAudit action to return the list. The beginform is only requesting the UpdateAccountDetails action.
You could do a jquery ajax request in the onSuccess function to request the GetAccountAudit action and update the html.
Could the two actions be combined so that the list would be returned in the UpdateAccountDetails view?

ASP.NET MVC.NET JQueryUI datepicker inside a div loaded/updated with ajax.actionlink

I'm trying to incorporate jqueryUI's datepicker inside a partialview like this:
<% using (Ajax.BeginForm("/EditData",
new AjaxOptions { HttpMethod = "POST",
UpdateTargetId = "div1" }))
{%>
Date:
<%= Html.TextBox("date", String.Format("{0:g}", Model.date), new { id = "datePicker"})%>
<% } %>
<script type="text/javascript">
$(function() {
$("#datePicker").datepicker();
});
</script>
When I directly call the url to this partial view, so it renders only this view the datepicker works perfectly. (For the purpose of testing this I added the needed jquery and jqueryui script and css references directly to the partial view)
But if I use a Ajax.Actionlink to load this partial view inside a div (called div2, submitting the above form should update div1) like this:
<div id="div1">
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" } )%>
</div>
<div2>placeholder for the form</div>
The datepicker won't appear anymore.
My best guess is the javascript included in the loaded html doesn't get executed,
($(document).ready(function() {
$("#datepicker").datepicker();
}); doesnt work either
If that's the case how and where should I call the $("datepicker").datepicker(); ?
(putting it in the ajaxoptions of the ajax.actionlink as oncomplete = "$(function() {
$('#datepicker').datepicker();});" still doesnt work.
If that's not the case, then where's my problem?
The answer given by veggerby probably will be working in the given scenario, therefor i marked it as correct answer.
My problem here was that the javascript is in a portion of html being dynamicly loaded thrue ajax. Then the loaded javascript code wont be picked up by the javascript interpreter (or whatever im supposed to call the javascript handling on the clientside).
In my case veggerby's sollution wouldnt work either but that's because in my app i even loaded that piece of html+javascript thrue ajax. which results in the same problem.
i didnt feel like putting the javascript in the first normally loaded page, since it doesnt always load the same piece of app (thus possibly executing code when its not needed).
i resolved this by creating a sepperate .js script which is included in the site.master:
function rebindJQuery(data) {
jQuery('#div2').html(data.get_data());
jQuery('#datepicker').datepicker();
return false; //prevent original behavior, in this case folowing the link
}
which gets executed by
<%= Ajax.ActionLink("Edit", "/EditData", new { id = Model.id }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div2" , oncomplete="rebinJQuery" } )%>
i have yet to find a way to get the UpdateTargetId into my rebindJQuery(data) function, so this can be more generic. Nontheless this solves my problem. (and a couple of compairable questions asked here on stackoverflow)
I don't know why that does not work, but you could skip using the Ajax.ActionLink and instead use JQuery on itself to do this task, i.e.:
<div id="div1">
<%= Html.ActionLink("Edit", "/EditData", new { id = Model.id } )%>
</div>
<div2>placeholder for the form</div>
<script type="text/javascript">
$(document).ready(function() {
$("#div1 a").click(function() {
$.get(
$(this).attr("href"),
null,
function (data) {
$("#div2").html(data);
$("#datepicker").datepicker();
});
return false; // to prevent link
});
});
</script>
jQuery live events might be useful.
http://docs.jquery.com/Events/live

Resources