Dropdownlist onchange event in ASP.NET MVC not using AJAX - asp.net

I'm trying to make use of the onChange event for my dropdownlist in my ASP.NET MVC project, althought it is not working.
The view, containing the form, looks like this:
#using (Ajax.BeginForm("Action", "Controller",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "pages",
InsertionMode = InsertionMode.Replace
}))
{
#Html.DropDownListFor(m => m.SelectedFrom, Model.ChangeFrom, new { onChange = "this.form.submit();" })
}
<div id="pages"></div>
With the code above, onChange fires when selecting an item in the dropdownlist as expected. Although it's not making use of ajax, it is simply redirecting me to a new page, instead of just updating/filling the "pages-Div".
Although...
If I delete the onChange event for the dropdownlist and add a simple submit button, like this:
#using (Ajax.BeginForm("SelectedUser", "ReplaceName",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "pages",
InsertionMode = InsertionMode.Replace
}))
{
#Html.DropDownListFor(m => m.SelectedFrom, Model.ChangeFrom)
<input type="submit" value="GO" />
}
it uses Ajax and only reloads the "pages-Div".
Am I missing something?
Regards,
Chris

I got it working by using jQuery instead:
onchange = "$(this.form).submit();"
Is there a better jQuery solution to this.form.submit();?

The first scenario redirecting you to a new page because you are performing a form.submit(), but are returning false so the action is running to completion. if you change new
{ onChange = "this.form.submit();" }
to
{ onChange = "this.form.submit(); return false;" }
you might have to write a tiny javascript function to make both calls.
But I don't think you want that because you aren't going to get the div replacement that the Ajax form will do for you. You'd have to wire that up yourself.
The second one stays on the page because that's how Ajax.BeginForm works. It knows that that input is tied to a Ajax form you are submitting and intercepts the call using the values in AjaxOptions.

Related

Rendering view in ASP.Net MVC

In my code I am using a partial view (call it PV1)
<div id="div_1">
<% Html.Partial("PV1", Model); %>
</div>
and in that partial view I am using "Ajax.BeginForm" to redirect it to a particular action, hence it is doing so ...
using (Ajax.BeginForm("action1", "Forms", null, new AjaxOptions { UpdateTargetId = "div_1" }, new { id = "form1" }))
{
Response.write("I am here.");
}
public ActionResult action1(XYZ Model)
{
//
return PartialView("PV1", Model);
}
at the last line of action I am again calling the same partial 'PV1', hence it is doing this too ...
but when rendering the view it don't print or do the steps written with in partial view, it override them with and show nothing ...
Html.Partial actually returns the result of rendering the view, you want to do <%= Html.Partial() %> or <% Html.RenderPartial(); %>
Html.Partial() returns the Html and thusly must be output on the page via <%= %> and Html.RenderPartial() uses Response.Write to output onto the page and can be used with <% %>.
This is not what you would use Ajax.BeginForm for. That helper is used to create actual <form> tags that will later be submitted to the server using MVC's unobtrusive ajax (so you still need some kind of a trigger action - a button, javascript - anything that submits the form).
I'm am not very clear on what you're trying to achieve. If you want to load a partial view with ajax, I would suggest using something like jQuery's ajax load method.

asp.net mvc razor yes no dialog not coming in razor

<%= Ajax.AjaxImageActionLink("../../Content/images/delete.png", "Feature", "Delete", new { id = item.int_FeatureId }, new AjaxOptions { UpdateTargetId = "table", HttpMethod = "Post", Confirm = "Delete Feature with Feature ID:" + item.int_FeatureId + " Feature Name:" + item.vcr_FeaturesName })%> pr
i am trying to generate javascript popup when pressing the delete link for yes and no. this works perfectly in .aspx views but how i can make it work in razor. i try to translate it but not working
#Ajax.ActionLink("Delete Profile", "Delete", new { id = item.int_UserId }, new AjaxOptions { UpdateTargetId = "UserTable", HttpMethod = "Post", Confirm = "Delete User with User ID:" + item.int_UserId + " User Name:" + item.vcr_UserName })
If you rewrite this in razor correctly and is not working, this is definitely not the case with aspx or razor. They're just parsers, and using any of them does not affect internal mvc code execution. Same on razor markup would be just remove aspx code end marker and replace start marker with '#'
#Ajax.AjaxImageActionLink("../../Content/images/delete.png", "Feature", "Delete", new { id = item.int_FeatureId }, new AjaxOptions { UpdateTargetId = "table", HttpMethod = "Post", Confirm = "Delete Feature with Feature ID:" + item.int_FeatureId + " Feature Name:" + item.vcr_FeaturesName })
I was having the following error and it seems to be something to do with the way the razor engine reads the jQuery function when you bundle or internally reference the scripts? I just referenced the files from the cdn and it works fine. This is the error you will likely get trying the former. Try referencing the jquery files from the cdn as this is probably your culprit.
Seems to work fine this way.
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

JavaScript action result no longer working after converting to partial view

Early yesterday, the following validation notice was working correctly. Then we converted the Index view where the request for this action originates to use a partial view, and the Delete ActionLink is now inside that partial view, and now the string argument to the JavaScript method call is rendered literally and as the only content on the 'destination' Delete view.
public ActionResult Delete(int id)
{
var perm = JobCardService.CheckBusinessRules(id);
if (!string.IsNullOrEmpty(perm))
{
return JavaScript("NotifyFailure('You may not delete this Installation: " + perm + "', false, 2000);");
}
JobCardViewData viewData = ViewDataFactory.CreateBaseViewData<JobCardViewData>("Installation List");
return View("Delete", viewData);
}
The Filter action returns the partial view, and is requested as below:
<div class="editor-field">
<% using (Ajax.BeginForm("Filter", "JobCard", new AjaxOptions { UpdateTargetId = "jobList" }))
{ %>
<%= Html.DropDownListFor(model => model.RequesterId, new SelectList(Model.RequesterList, "RequesterID", "CompanyName", Model.RequesterId), new { onchange = "$('#Select_Save').click();" })%>
<input id="Select_Save" type="submit" value="Save" style="display: none" />
<%
}%>
</div>
If the action method is responsible for returning a view, seems like the response shouldn't be returning a JavaScript if in error because no underlying ASP.NET page would be served, which means that you would see it as literal text.
Consider assigning the method call to ViewData, and in your client do something like:
<% if (ViewData["X"] != null) { %>
<script type="text/javascript">
<%= ViewData["X"] %>
</script>
<% } %>
Calling VIewData["X"] like I do should render the JavaScript code directly and get directly executed when parsed.
I think that might work; you can always utilize other mechanisms like eval to parse content, or do whatever else you might need....
Refer to the comment of this question ASP.NET MVC Javascript ActionResult
The other aspect is that using this return type is considered to be an anti-pattern and should be avoided. The suggested approach is to use a Json result.
Working example for JavaScriptResult in asp.net mvc
http://devlicio.us/blogs/billy_mccafferty/archive/2009/02/07/beware-of-asp-net-mvc-javascriptresult.aspx
Edit:
Since javascript is being returned from the Controller, an alternative would be to send script back to the browser that redirects the user to the correct page.
public ActionResult Delete(int id)
{
var perm = JobCardService.CheckBusinessRules(id);
if (!string.IsNullOrEmpty(perm))
{
return JavaScript("NotifyFailure('You may not delete this Installation: " + perm + "', false, 2000);");
}
// you may need to do a bit more to create a URL in the form of http://...
UrlHelper u = new UrlHelper(this.ControllerContext.RequestContext);
string url = u.Action("ActionName","ControllerName", new{id=1}); // the new Action will return the delete view
return Javascript(String.Format("window.location =""{0}"",url);
}
Refer to Creating a URL in the controller .NET MVC for more on the UrlHelper.
This may not be the best way to do this, but every other answer I have come across has required extensive rework to achieve. This requires one small, simple change and works exactly as required. All I had to do was change the Delete action link from this:
<%= Html.ActionLink("Delete", "Delete", new { id = item.InstallationDBNumber }) %>
to this:
<%= Ajax.ActionLink("Delete", "Delete", new { id = item.InstallationDBNumber }, new AjaxOptions { HttpMethod = "Get" }) %>

ASP.NET MVC 2 Client validation function in Ajax form

My problem is the following:
I'm using client validation function of the MVC 2.0 framework.
Everything is nice, when I use the validation in a simple form.
But when I use an Ajax form, and I update the fields of the ajax form, the client validation doesn't work.
I think about, I have to refresh the validation after the ajax call but I don't know how I should do it.
Anybody can help me?
this happens because the window.mvcClientValidationMetadata fills in a different "scope" than the jquery validation or mvc client validation functions. I have solved this with jquery validation adding the following line before the ajax.begin form. Like this:
<div id="result"></div>
<% Html.EnableClientValidation(); %>
<% using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
// here goes the form
<input type="submit" value="Create" />
<% } %>
this is the required code that needs to be added:
<script type="text/javascript">
function RefreshClientValidationMetadata() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
}
RefreshClientValidationMetadata();
</script>
Of course the function RefreshClientValidationMetadata() can be added in any place.
Hope this help!
Try this:
$(document).ajaxComplete(function () {
$.validator.unobtrusive.parse(document);
});

asp.net mvc complex ajax updates

i'm wanted to perform some ajax calls in a certain way.
I have a page. In this page are 2 ViewUserControls, say control1 and control2.
control1 has a list of Ajax.ActionLinks that call control2 like this:
<%= Ajax.ActionLink(page.Name, "PageDetails", new { pageSysName = page.SysName }, new AjaxOptions { UpdateTargetId = "pageEdit" })%>
control2 has an Ajax form which updates fine. The Ajax.BeginForm method looks like this:
Ajax.BeginForm("SavePage", "Admin", new AjaxOptions { UpdateTargetId = "pageEditUpdated" })
When a user hits the Save button, it currently updates a div called pageEditUpdated with a basic Content("updated") return type from the Controller.
The part i'm stumped on is how to update control2 to reflect the new changes.
To sum it up, a Page has 2 controls. I'd like control2 to refresh itself and also update a div to notify the user that the update has been performed.
Have your SavePage method return a partial that reflects the updated form contents, including the update message. Have the update target be the "inner container" of the form.
<% Ajax.BeginForm("SavePage", "Admin", new AjaxOptions { UpdateTargetId = "innerForm" }) { %}
<div id="innerForm">
<% Html.RenderPartial( "EditPageContents" ) %>
</div>
<% } %>
Your save action should then return
updatedModel.UpdateMessage = "updated";
return PartialView( "EditPageContents", updateModel );
and your partial view should have
<% if (!string.IsNullOrEmpty( UpdateMesage )) { %>
<%= Html.Encode( UpdateMessage ) %>
<% } %>
Honestly, though, this would be a lot easier using jQuery to post the form via AJAX:
$(function() {
$('form').submit( function() {
$.post( $(this).attr('action'), $(this).serialize(), function(data) {
$('#updateMessage').html(data).show();
});
return false;
});
});
I have to second tvanfosson's comment (I'd vote for him, but my reputation apparently isn't high enough yet). At any rate, when I integrated Ajax functionality with my MVC site I found the Microsoft provided Ajax methods to be fairly clunky. So instead I switched to using the jQuery.form plugin (good examples here). I found it made things much easier to work with. I just created MVC user controls for the section of page I wanted to be ajax, and just reloaded that user control as neccessary.

Resources