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?
Related
I want to redirect to an action afer the execution of create method
so the create method returns this:
return Json(new
{
Data = base.RenderView("_Forme ", model),
Message = (string)TempData[TEMP_DATA_MESSAGE_KEY],
Result = (AjaxResultType)TempData[TEMP_DATA_CODE_KEY]
}, JsonRequestBehavior.AllowGet);
}
Layout page:
<div> #Html.Partial("_Forme") </div>
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
**In the View: _Forme.cshtml **
<a href="#Url.Action("Create", "Uneform")"
#if (Model.nouveau==true)
{ Create}
{ Update }
</a>
I want to be able to refrech the layout page and display all the partial views.
I already try redirect to action using javascript didn't work,any help
If you want to refresh only some part of the layout page, wrap that in a container div and make an ajax call to get the new markup for this area
<div id="updatable">
#if (#Model.nouveau==false)
{
<div> #Html.Partial("_Onglet") </div>
<div> #Html.Partial("_Details") </div>
}
</div>
and in your ajax call's success event, you may use the $.load method
$("#updatable").load("/Home/GetUpdatedHeader");
Assuming GetUpdatedHeader action method return a partial view which has the other 2 partials in it.
If you simply want to reload the same page, you can do this in javascript.
window.location.href = window.location.href;
You can do this is in your ajax call's success event.
If you want to redirect to another action/page
window.location.href ="/Home/Index"; //Replace this value with your url
You may also send the url for your new page in the json response(You can use the UrlHelper to build the urls) and use that for the redirect.
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>
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.
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
I have a simple ASP.Net MVC View which contains an FCKeditor text box (created using FCKeditor's Javascript ReplaceTextArea() function). These are included within an Ajax.BeginForm helper:
<% using (Ajax.BeginForm("AddText", "Letters",
new AjaxOptions() { UpdateTargetId = "addTextResult" }))
{%>
<div>
<input type="submit" value="Save" />
</div>
<div>
<%=Html.TextArea("testBox", "Content", new { #name = "testBox" })%>
<script type=""text/javascript"">
window.onload = function()
{
var oFCKeditor = new FCKeditor('testBox') ;
var sBasePath = '<%= Url.Content("~/Content/FCKeditor/") %>';
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ToolbarSet = "Basic";
oFCKeditor.Height = 400;
oFCKeditor.ReplaceTextarea() ;
}
</script>
<div id="addTextResult">
</div>
<%} %>
The controller action hanlding this is:
[ValidateInput(false)]
public ActionResult AddText(string testBox)
{
return Content(testBox);
}
Upon initial submission of the Ajax Form the testBox string in the AddText action is always "Content", whatever the contents of the FCKeditor have been changed to. If the Ajax form is submitted again a second time (without further changes) the testBox paramater correctly contains the actual contents of the FCKeditor.
If I use a Html.TextArea without replacing with FCKeditor it works correctly, and if I use a standard Post form submit inplace of AJAX all works as expected.
Am I doing something wrong?
If not is there a suitable/straight-forward workaround for this problem?
The problem is unrelated to MVC but caused by using FCKeditor in conjunction with AJAX. To fix in the code above I added the following to the submit button's onclick event:
<input type="submit" value="Save" onclick="FCKeditorAPI.GetInstance('TestBox').UpdateLinkedField();" />
For more information see here.