I have a problem concerning Asp.net MVC.
I have an Index.cshtml page with the following javascript
$('#employeeTable tbody').on('dblclick', 'tr', function() {
var mitarbeiterId = table.row(this).data().Id;
$.post('#Url.Action("IndexCompletion")', { id: mitarbeiterId });
});
This basically just gets me the id of an employee and calls this ActionResult in my Controller
[HttpPost]
public ActionResult IndexCompletion(int id)
{
Mitarbeiter ma = new LeistungserfassungService.LeistungserfassungService().GetMitarbeiterById(id);
return View("IndexCompletion", new IndexCompletionViewModel{Mitarbeiter = ma});
}
Now i hoped that this will show me the following page:
#model Leistungserfassung.Models.IndexCompletionViewModel
#{
ViewBag.Title = "Completion";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="content">
<h2>Completion</h2>
#Model.Mitarbeiter.Nachname
</div>
But what happens now is, it builds the page successfully, as i can see on the networking tab in Google Chromes dev tools, but does not redirect to it.
Also when i directly try to navigate to this .cshtml file, the browser tells me it can not be found.
Does anyone have an idea of what could be the problem on this?
I am very new to javascript so i am grateful for any advice!
Thanks in advance and sorry for the german parts in my code.
You're making an async ajax call to the server using JavaScript this means JavaScript needs to redirect the user to another page. So, in order for this to happen your controller post method should return a response to JavaScript (most likely JSON) which will have a redirect link (key, value) item to then redirect.
I hope this helps you.
var jsonObj = JSON.stringify({
'id': mitarbeiterId
});
$.ajax({
url: '#Url.Action("IndexCompletion")',
type: "Post",
data: jsonObj,
async: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#divForReturnedViewFromController").html(msg);
},
});
Thanks for your help guys.
Now that i understand that $.post creates an AJAX call, I changed my code to create a form on Doubleclick and submit it with my Id.
(Which is the far better way to solve this problem)
$('#employeeTable tbody').on('dblclick', 'tr', function () {
var mitarbeiterId = table.row(this).data().Id;
$('<form action=#Url.Action("IndexCompletion") method="POST">' +
'<input type="hidden" name="id" value="' + mitarbeiterId + '">' +
'</form>').submit();
});
This works great. Thanks again for your help.
Related
That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.
I am using jquery ajax to post a html form . This works fine with Chrome and not with Firefox . When I analyze the issue ,the query parameter "Accept=Apply" is not shown in Firefox dev tool (Params tab)but I could see the proper string is in debug statement which i have added. Can anyone help on this?
Jquery :
function postSettings() {
var frm_data = $("#MyForm").serialize() + "&Accept=Apply";
console.log("frm_data >>"+frm_data);
var myobject = {"Accept":"Apply"};
var testdata =$("#MyForm").serialize() + '&' + $.param(myobject);
console.log("testdata >>"+testdata);
$.ajax(
{
type: "POST",
url: "https://10.20.12.30/Update.cgi",
data: frm_data,
success: function (successData) {
console.log("successData >>"+successData);
} else {
console.log("errorData1 >>"+successData);
}
},
error: function (errorData) {
console.log("errorData2 >>"+errorData);
}
});
}
Thanks
Best way to do this would be adding it as a hidden field
<input type="hidden" id="Accept" name="Accept" value="apply"/>
This way we can aviod passing it as query string and unexpected issues.
I'm relatively new to web app development, javascript and MVC so please bear with me.
I want to use the Jquery.Ajax command to post my Model to my controller.
My View:
#model MVC_Interface_May21.Models.DataValuesViewModel
...
<form method="post" id="testForm">
<input type="submit" class="subButton" value="Add New.." />
</form>
...
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
$(document).ready(function () {
$('#testForm').submit(function (e) {
e.preventDefault();
#{var val = Json.Encode(Model);}
var check = '#Html.Raw(val)';
$.ajax({
url: 'Results/AddNew',
type: 'POST',
//data: JSON.stringify(check),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
}
...
</script>
I haven't included the code for my Model or Controller because I don't believe they are a part of the problem. Currently, my code simply posts back to the same page. As far as I can tell the ajax command is not being executed. The debugger doesn't help me in tracing the behavior, and I am assuming that the form is simply doing it's post submit and ignoring my function.
Any help is much appreciated, and I'm sorry if this has been answered in the past. I developed my code by looking at other solutions, but I can't identify what's making mine dysfunctional.
You have to read more about it MVC, im not even sure what you are trying to do serializing the Razor Model like that, but that is what you are getting from the server, not your HTML Form with whatever the user input is.
You can use this js function to submit a form with Ajax.
$(function () {
$('#myForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
And use the Create Form and imput helpers/
#Html.BeginFor
#Html.EditorFor
I am working on an ASP.NET MVC3 application.
I am attempting to POST to a method that returns a bunch of data using the jQuery.ajax api; however whenever the request is handled by the server my form collection's keys count is 0 and so my view model isn't populated which is a problem.
I am applying applying the ajax to my form's submit like this:
$(document).on("submit", "form", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: this.action,
data: form.serialize(),
contentType: "application/html; charset=utf-8",
dataType: "html",
success: function (result) {
var d = new Date();
var str = d.toString() + result;
$('#dynamicContent').html(str);
}
});
});
My form is created like this:
#Using Html.BeginForm("GetContent", "TheController", FormMethod.Post, New With {.id = "GetContentForm"})
#Html.DropDownListFor(Function(model) model.SelectedTypeID, New SelectList(Html.NullListItemOptionList(Model.TypeOptions.ToList, "Please Choose"), "ID", "Name", Model.SelectedTypeID), New With {.onchange = " $(this).parents('form').submit();"})
#<input type="submit" value="Refresh" style="cursor: pointer" />
End Using
<div id="dynamicContent">
</div>
My controller method is:
<HttpPost()>
Function GetContent(ByVal collection As FormCollection) As PartialViewResult
Dim itemsVM As New ItemsViewModel
TryUpdateModel(itemsVM, collection)
Return PartialView("PartialItems", itemsVM)
End Function
It's almost as if the serialization of the form is not working but I don't know how to fix this. I would really appreciate some insight into why this isn't working.
Thank you.
Since you're sending form params, the contentType you are using is incorrect, which in turn causes the server to not receive your data because it's expecting html and is not receiving any. To solve it, simply remove the contentType option from $.ajax.
i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.