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.
Related
I want to send an image and a number when the user perform an upload.
My Javascript
form.append('file', $(uploader).get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
$.ajax({
method: 'POST',
url: '/images/send',
data: form,
form: false,
processData: false
});
In my action what should I do?
With this I only receive the image.
[HttpPost]
public string send(IFormFile file) // What argument should I use
{
How do I get the number and file?
}
You can add a new parameter of type int to your action method. The parameter name should match with the formdata item name you are sending (id)
[HttpPost]
public string send(IFormFile file,int id)
{
// to do : return something.
}
You need to have the contentType property on your $.ajax method set to false
This should work.
var form = new FormData();
form.append('file', $('#File').get(0).files[0]);
var id= $("#id").val();
form.append("id", id);
var urlToPost ="/images/send";
$.ajax({
method: 'POST',
url: urlToPost ,
data: form,
processData: false,
contentType: false
}).done(function(result) {
// do something with the result now
console.log(result);
}).fail(function(a, b, c) {
alert("error");
});
If you want to send multiple input values with the file input, i suggest you create a view model and use that as explained in this post.
Also it might be a good idea to keep your form elements inside a form and set it's action value to the url you want to send and read that in your javascript code that hard coding it there.
<form asp-action="send" asp-controller="images" method="post">
<input type="file" name="File" id="File" />
<input type="text" id="id" value="0" />
<input type="submit" />
</form>
Now in your javascript you can read it from the form. For example, if you are wiring up the submit event of the form
$(function () {
$("form").submit(function (e) {
e.preventDefault();
var urlToPost = $(this).attr("action");
//your existing code for ajax call
});
});
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.
The question is pretty straightforward: I use #Html.EditorForModel() to generate fields for my model. Then user fills all these fields and I want to send this field via AJAX, becuase I should do several server's services without page reload.
I googled several approaches, but it seems that there is no standard way to do such things. I mean I do not have an object on client-side that represent model. I found one single library calls JSModel (link) but it seems to be not working. My code for now is:
#model Student
<script src="#Url.Content("~/scripts/jquery-1.12.2.min.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/Requester.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/jsmodel.js")" type="text/javascript"></script>
<script type="text/javascript">
var requester = new Requester(#Html.Raw(Json.Encode(new Student())));
function SendSignupRequest() {
requester.SendSignupRequest();
}
</script>
<h2>Student</h2>
<div>
#Html.EditorForModel()
</div>
<input type="button" value="Send" onclick="SendSignupRequest()"/>
Requester.js:
function Requester(rawModel) {
this.modelObj = new JSModel(rawModel);
this.SendSignupRequest = function() {
var model = modelObj.refresh();
var val = model.prop("Name");
alert(val);
}
}
Is there any easy way to serialize a model object in JSON and send it to server, without manually constructing an object with millions of document.getElementById?
View
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { #class = "form-horizontal form-compact ", role = "form", id = "form1" }))
{
}
Java Script
var formdata = $("#form1").serializeArray();
$.ajax({
url: url,
type: 'POST',
data: formdata,
success: function (data) {
}
Controller
public ActionResult action(Model model)
{
//access data here
}
You can serialize your form to a JSON object with jQuery:
var data = $('form').serialize();
(This would, of course, mean wrapping your form elements in a form, which really should be happening anyway.)
Then just pass that data object to the server in the POST request. Something as simple as:
$.post('some/url', data, function(response) {
// success callback
});
without manually constructing an object with millions of document.getElementById
Note that if your object has millions of fields then you may very well encounter other problems here.
Yes you can use form serialize using Jquery
var formData = $('#form').serializeObject();
$.extend(formData, { Contacts : myContacts});
$.extend(formData, { Address : myAddress});
var result = JSON.stringify(formData);
$('#formHiddenField').val(result);
then submit form using:
$.ajax(
url: #Url.Action("post url")
data: myForm.serialize(),
dataType: 'json',
type: 'POST',
success: function(){
})
Why not Ajax.BeginForm() for your purposes. I believe model binding works automatically.
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 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.