Load partial view into div on button click without refreshing page - asp.net-mvc

I know this question might be repeated but my query is different let me explain, I have a drop down in page and by selecting value in drop down list,and I click on submit button.. I want by click on submit button I need to load partial view in tag that is list of records of selected drop down list value.
i tried this :
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Content("~/Search/MDLNoDataList")',
data: mdlno,
success: function (data) { $("#viewlist").innerHtml = data; }
});
});
but not getting result And I m using these many jquery plugins
<script src="../../Scripts/jquery-migrate-1.0.0.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>

If i understand correctly, below is what you need to do.
HTML Example:
<div id="records">
</div>
<select id="ddlRecordType">
<option value="1">Type 1</option>
<option value="2">Type 2</option>
</select>
<input type="submit" value="Load Records" id="btn-submit" />
jQuery Code
$(document).ready(function(){
$('#btn-submit').click(function(){
var selectedRecVal=$('#ddlRecordType').val();
$('#records').load('/LoadRecords?Id='+selectedRecVal);
return false; // to prevent default form submit
});
});
Here ?Id= is the query string parameter passed to server to get
the selected item in dropdown.
Edit: The below answer was added, as the question content changed from initial post
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList","Search")',
data: mdlno,
success: function (data) {
// $("#viewlist")[0].innerHtml = data;
//or
$("#viewlist").html(data);
}
});
return false; //prevent default action(submit) for a button
});

Make sure you cancel the default action of form submission by returning false from your click handler:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("MDLNoDataList", "Search")',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
And if you are using the WebForms view engine and not Razor make sure you use the correct syntax to specify the url:
$("#btnclick").click(function () {
$.ajax({
type: 'POST',
url: '<%= Url.Action("MDLNoDataList", "Search") %>',
data: mdlno,
success: function (data) {
$("#viewlist").html(data);
}
});
return false; // <!-- This is the important part
});
If you do not return false, the form is simply submitted to the server when you click on the submit button, the browser redirects away from the page and obviously your AJAX call never has time to execute.
You will also notice some improvements I made to your original code:
Using the Url.Action helper when pointing to a server side controller action in order to take into account routes defined in your application.
Using jQuery's .html() method instead of innerHTML to set the contents of a given element.

You need AJAX for this purpose.
$.get(url, data, function(data) { $(element).append(data) });
and Partial View that is vague.
element {
overflow:hidden;
}

Related

Use a Function That Returns Ajax to Ajax.BeginForm's onBegin

EDIT: To be more clear, I am looking to have onBegin call a function that returns a true or false value from an Ajax call. That false value needs to be able to trigger onBegin to abort the form submission, just as if I had returned a false value from a non ajax function.
I need to return a value of false to Ajax.BeginForm's onBegin, if certain conditions exist. This way I can prevent the form from submitting if certain database conditions exist.
However, in order to use the results of an Ajax Get, I would need to craft the function to use callbacks, which means that I cannot have the function used by onBegin return the ajax value. So how can I pass the result into onBegin?
Basically I have:
`Ajax.BeginForm(onBegin="checkIfMyConditionExists();"`}...
function checkIfMyConditionExists(){
$.get(checkConditionURL, function(data){
doSomething(data);
});
How can I get that data (which would be my true or false value) into onBegin?
What you are trying to accomplish without it being synchronous just is not going to happen. You WILL have to perform a synchronous check. Otherwise the check will be called but the form and other things will be submitted before the ajax call has time to say "Wait for me."
In your ajax call to the server you have to set async: false on a $.ajax call. This will make it to where it will expect some sort of result before running the next bit of code. Keep in mind that you wouldn't want to do $.get because there is no option to turn it off.
If you "don't want the UI to hang".... Put some sort of loading icon or text. It's a good practice for "ajax" stuff anyways...
Here is the code you could use :)
function checkIfMyConditionExists () {
$.ajax({
url: checkConditionURL,
async: false,
success: function (data) {
if (!data.success) {
return false;
}
// put your code to run something here!
}
});
}
It really doesn't need to be more complicated than that. Also something to keep in mind when implementing this...
Per the jQuery.ajax documentation:
As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
Another way to accomplish this would be to do the following.
Use a standard button on the form. (not a submit)
<button id="TriggerButton">Submit</button>
Handle the click of that button. Do your check. Submit the form if it's success!
$(function () {
$("#TriggerButton").click(function (e) {
e.preventDefault();
$.ajax({
url: checkConditionURL,
success: function (data) {
if (!data.success) {
// ruh roh!
return false;
}
// submit le form!
$("#MyForm").trigger("submit");
}
});
});
});
With this method, you could remove the onBegin and it should do what you need it to do. :)
I modified your code with a solution that works:
Ajax.BeginForm(onBegin="return checkIfMyConditionExists();"}...
function checkIfMyConditionExists(){
$.ajax({
url: checkConditionURL,
data: data,
async: false,
success: function (data) {
return data.condition;
}
});
note the async: false option that allows you to wait until the call ends and get the results after that.
My Working code
JavaScript/JQuery
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function StartValidation() {
var result = AjaxCall();
return result;
}
function AjaxCall() {
var Istrue = false;
$.ajax({
url : "#Url.Action("Json", "FileUpload")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({FirstName:'test', LastName:'test1'})
}).done(function() {
Istrue = true;
alert('ok')
})
.fail(function() {
Istrue = false;
alert('not ok');
});
return Istrue;
}
</script>
HTML
#using (Ajax.BeginForm("UploadRequestFile", "FileUpload", new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "return StartValidation();"
}, new { id = "frmUp" }))
{
<input type="submit" name="Submit" value="Submit" />
}
Runtime MarkUp
<form method="post" id="frmUp" data-ajax-method="POST"
data-ajax-begin="return StartValidation();" data-ajax="true"
action="/fileupload/UploadRequestFile?Length=10">
<input type="submit" value="Submit" name="Submit">
</form>
Check the data-ajax-method, data-ajax-begin and data-ajax attributes. Ajax.BeginForm helper emits those attributes. Those attributes mean absolutely nothing to the browser. It's the jquery.unobtrsuive-ajax.js script that understands and interprets them. Without it. So, no need to perform the Submit explicitly.
Action Methods
[HttpPost]
public JsonResult Json(string FirstName, String LastName)
{
//Do the Validation Part here.
return Json(new { Success = true });
}
[HttpPost]
public ActionResult UploadRequestFile()
{
return View();
}

knockout.js redirect in view model

I have the following code on cshtml page.
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" onclick="location.href='#Url.Action("ExportInventory", "Inventory")'">EXPORT INVENTORY</button>
</div>
How do I make this work in my view model?
I think I almost got it, but need some help
<div class="buttons">
<button type="button" id="export" class="export-inventory-button" data-bind="click: exportInventory">EXPORT INVENTORY</button>
</div>
My viewmodel has this code:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: '/Inventory/ExportInventory', type: 'POST' }).done(function (data) {
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
I tried this, but I get errors:
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
$.ajax({ url: 'location.href="#Url.Action("ExportInventory", "Inventory")"', type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
Can someone help me figure this out?
The way you're trying to pass in the url to the ajax call is probably not working the way you expect. Also, you wouldn't need the location.href= to be part of the url parameter in the $.ajax() call.
If your view model is coded in a script tag right in your cshtml page, you can try this:
<!-- cshtml razor view code for generating the html is above this line -->
<script>
var viewModel = {
function exportInventory() {
filtererGridData = vm.details;
var json = ko.mapping.toJSON(vm.details);
//allow razor to build a javascript string for you when it renders the html
//when the browser parses this script, it will just see a simple string
var myURL = '#Url.Action("ExportINventory", "Inventory")';
//pass your variable to the jQuery ajax call
$.ajax({ url: myURL, type: 'POST' }).done(function (data) {
window.location.href = responseText.url;
//this line of code would never be called because the browser has navigated away from this page...
$('#export').html(data);
}).fail(function (data) {
toastr.warn('Could not export data, please contact LGL.');
});
}
};
</script>
Load the page and view source. If the var myUrl = line is the correct URL to your controller as a string, then you know that razor kicked in and prepared that for you on render.

Html imput type="image" onclick event

Friends I have a problem
We need to make a user control that has the ability to delete itself, I made it but we did not clear the mechanism for removal, it should be tied to a nice picture. Code that is attached to the frame is given below, but not
$('#delete').bind('click', function () {
alert('test');
var urlA = '<%=Url.Action("DeleteMessage","Ticket")%>';
$.ajax({
url: urlA,
type: 'POST',
data: { idMessage:$(this).parents("div:first").find("input[name='MessageID']").val(),idticket:$('#TicketID').val() },
success: function (data) {
alert(data);
}
});
});
But when I write this, but to throw me to the homepage what's wrong
$('#delete').live('click', function ()
$("#delete").live("click", function(){
//code
$(this).remove(); //delete itself
});
If your image is declared as input type="image" then it will behave like a submit button and submit your page. You should prevent the default behavior of submitting the page by adding an event.preventDefault() or equivalent to your javascript function.

Rails delete link JavaScript ajax call

I want to create an ajax delete call. When the link is clicked, the confirm box should appear and then the p tag fades out (comment). The problem is just how the ajax call should be and how to show the confirm box.
HTML view:
<a rel="nofollow" data-method="delete" data-confirm="Er du sikker?" class="softdelete" href="/blogs/5/comments/18">slet</a>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('.softdelete').click(function () {
var Url = $(this).attr('href');
var Data = $(this).attr('data-method');
$(this).closest('p').fadeOut(1000);
$.post(Url);
return false;
});
});
</script>
When clicked on the delete link, the comment fades out, but it is not destroyed. Also no confirm box appeared.
You're using a post request, so the action isn't properly routed: Rails expects a delete request.
Here is the way to proceed with jQuery:
$.ajax({
url: your_url,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});

jQuery not submitting my form to an asp.net mvc controller

I'm trying to submit a form via ajax to an MVC controller.
HTML
<% using (Html.BeginForm("AskQuestion", "Home", FormMethod.Post, new { id="submitquestion"})) {%>
jQuery
$("#submitquestion").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
I'm getting no javascript errors, and my controller is not getting hit when I set a breakpoint. However, if I just set this:
$("#submitquestion").submit();
The form submits.
What am I doing wrong? I want to submit the form via .ajax
Add new html button to submit and wirte your ajax submit in the click event like this,
$("#yourButton").click(function(event) {
event.preventDefault();
var form = $('#submitquestion');
$.ajax({
url: '<%= Url.Action("AskQuestion", "Home") %>',
type: "Post",
data: form.serialize(),
success: function(result) {
if (result.success) {
//success method
}
}
});
});
for submitting via ajax. add a button to html form
<input type="button" name="button" value="Test" id="test" />
And your jquery script should be like this,
$('#test').click(function () {
var formCollection = $(this).parents('form').serialize();
$.post('your url', formCollection, function (result) {
alert(result);
});
});
Hope this helps.

Resources