I have an MVC3 Razor form in index.cshtml using HtmlHelper. It works, but I want to replace it with Ajax form using AjaxHelper (note: I am still not familiar to Ajax/jQuery). It fails. My questions:
What's wrong with my code?
Are there any good websites that explain this kind of transformation?
If one transforms a view to Ajax processing, is it necessary to change the controller as well?
Here's my index.cshtml file. My trial with Ajax is commented out below the MVC3 form.
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
#using ( Html.BeginForm("UploadFile", "Home", FormMethod.Post, new
{
enctype = "multipart/form-data"
}) )
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Select a file</legend>
<input type="file" id="fileupload" name="fileuploadname" />
<p>
<input type="submit" value="Upload" id="upload" onclick="javascript:document.getElementById('upload').disabled=true; document.getElementById('upload').value='Uploading...'" />
</p>
</fieldset>
}
#* #using ( Ajax.BeginForm("UploadFile", "Home",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}) )
{
<input type="file" id="fileupload" name="fileuploadname" />
<p>
<input type="submit" value="Upload" id="upload" onclick="javascript:document.getElementById('upload').disabled=true; document.getElementById('upload').value='Uploading...'" />
</p>
}
*#
Thx in advance.
You can't upload files using Ajax. At least not directly.
There are of course few plugins that help you with this, but they qork outside of AjaxHelper scope. This simply means you will have to get your hands dirty with jQuery which is also a good thing. It's a simple and small library and while getting acquainted with it you'll most likely deviate away from AjaxHelper and rather just use jQuery (with HtmlHelper).
Related
To edit a record, I'm opening a modal Kendo UI window populated with a partial view containing an AJAX enabled form:
#model MVC_ACME_Hardware.Models.BaseModel
<script type="text/javascript">
$(function () {
$("form").kendoValidator();
});
</script>
#using (Ajax.BeginForm("EditProduct", new AjaxOptions { UpdateTargetId = "ProductDiv", OnSuccess = "SomeMethod" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeFTE</legend>
#Html.HiddenFor(model => model.Products.Product_ID)
<div class="editor-label">
#Html.LabelFor(model => model.Products.Product_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Products.Product_Name)
#Html.ValidationMessageFor(model => model.Products.Product_Name)
</div>
<input type="submit" value="Save" class="myButton" />
</fieldset>
}
When I run the form and click 'Save' on the popup, the form posts successfully but the post is not done via AJAX and my 'SomeMethod' onsuccess method is not being called. I've tried adding...
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
...on the partial view but it did not help. How can I get my form to submit using AJAX? I'm missing something obvious. Thanks!
try something like this (attention to the input type):
<input type="button" value="Save" class="myButton" id="btnSave" />
and the in the $(document).ready() :
var validator = $(document.forms[0]).kendoValidator().data("kendoValidator");
$("#btnSave").click(function(e) {
if (validator.validate()) {
var formContent = $(document.forms[0]).serialize();
var url = $(document.forms[0]).action;
$.post(url, formContent).done(function(data) {
$(document.body).append("<div class='savedRecordMessage'>success</div>");
});
}
});
I think you need to add these files if you want to use unobtrusive validation of MVC and Ajax options of AJAX form.
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
I am trying to use Ajax.Actionlink to render a partial view. But it only redirects me to the partial view. I also added: <add key="UnobtrusiveJavaScriptEnabled" value="true" /> to webconfig. Anyone?
My layout.cshtml Scripts.render and script is in head tag. Ajax.actionlink and div is in body
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/Scripts/jqueries")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#Ajax.ActionLink("Ajax Click", "Document","Home", new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace })
<div id="result">
</div>
Home controller:
public PartialViewResult Document()
{
return PartialView("Document", om);
}
My Document.cshtml
#model mymodel
#foreach (var item in Model)
{
<li>#Html.ActionLink(item.something, "Controller", "Action")</li>
}
Your jquery and unobtrusive-ajax should be at the bottom of the page, like this
</footer>
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#RenderSection("scripts", required: false)
</body>
</html>
Information why can be found here
http://developer.yahoo.com/performance/rules.html/
Placing this at the wrong place, WILL result in errors
I am using
<script src="http://malsup.github.com/jquery.form.js"></script>
for my ajax form upload.
When I upload file without the Codeigniter framework this works fine. But when I used it within the frame work it shows me the following error :-
HTTP wrapper does not support writeable connections
plus it is actually loading a separate page
Here's my code :-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
clearForm: true,
resetForm: true
};
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
//alert("Thank you for your comment!");
});
$('#myForm').ajaxForm(options);
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="comment.php" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<br />
<textarea name="comment"></textarea>
<br />
<input type="file" value="Share a Pic" name="file" id="file" />
<br />
<input type="submit" value="Submit Comment" />
</form>
</body>
For Codeigniter I changed the action to
site/submit_myform
So it loads site/submit_myform. Site being my controller. other values are being stored in the database
Thanks
The ajax part isn't working if the page is redirecting. You need to return false; during the on submit to prevent the page from redirecting.
I would suggest following the ajaxSubmit()example provided in the form plugin.
I am developing in asp.net mvc and today I saw some strange thing in using ajax helpers.
If I use Ajax.BeginForm(...) or Ajax.ActionLink(...), they do not call (post to) the actions asynchronously, and they work as they are normal form or normal link, but when I check Request.IsAjaxRequest() in action, it returns true.
For ajax forms, I use
$('#createqfrm').submit(function () {...}
and it works fine, and send the form asynchronously.
Note: I know I have to change .live() to .on() in jquery.unobtrusive-ajax.min since new versions of jquery.
also here are my referenced java libs:
<script src="#Url.Content("~/Scripts/jquery-1.9.0.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Edited:
Checking Request.IsAjaxRequest() and saw that it returns false.
Action Code Added:
public ActionResult GetStriing()
{
if (Request.IsAjaxRequest())
{
return Json("ajax called",JsonRequestBehavior.AllowGet);
}
else
{
return Json("ajax not called", JsonRequestBehavior.AllowGet);
}
}
part of html code for form:
<form action="/admin/xxxx/create" data-ajax="true" data-ajax-success="handeCreateQuestionnareSuccess" id="form0" method="post"> <div class="editor-label">
<label for="Title">title</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="*" id="Title" name="Title" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Title" data-valmsg-replace="true"></span>
</div>
<div class="editor-label">
<label for="Status">Status</label>
</div>
....
<script type="text/javascript">
function handeCreateQuestionnareSuccess(context) {
debugger;
if (context) {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("#CreateQuestionnarieform").append('<input type=hidden name=questionnarieid value=' + context[2] + '/>');
} else {
$("#CreateQuestionnarieform").empty().html(context[1]);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
}
}
</script>
Code that submits form with ajax call:
$('#createqfrm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (context) {
}
});
}
return false;
});
not a solution but can notify other users:
The problem is with jquery 1.9.0 and updates that I get from nuget for jquery.validate.min.js and jquery.validate.unobtrusive.min.js I changed back to 1.8.3 and it works fine.....
Well that sounds like UnobtrusiveJavaScriptEnabled is set to false. Have a look in your AppSettings-File. In section <appsettings> there should be:
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
EDIT:
Just found this link after a minute of googling:
http://forums.asp.net/t/1877166.aspx/1?jquery+unobtrusive+ajax+js+error+with+jQuery+1+9+0+updated
Unobtrusive Ajax stopped working after update jQuery to 1.9.0
I have page with form:
#using (Html.BeginForm("Create", "Theme", FormMethod.Post, new { id = "frm_post", enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(m => m.Name)
<input type="image" src="img.png"
onclick="javascript:if(func()){document.getElementById('frm_post').submit();}else{return false;}"/>
}
I included scripts to page:
<script src="#Url.Content("~/Scripts/jquery-1.5.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
I have such strings in web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
I have [Required] for Name in Model.
But when I left textbox Name empty and submit form, error message is shown for some seconds and then page reload. How can I stop reloading of page?
O-o-ops... I just should remove form.submit() from onclick event of my button.
So, if I use
<input type="image" src="img.png"
onclick="javascript:if(!func()){return false;}"/>
it works fine.
It looks like you might want to remove that inline onclick handler and consider writing instead a custom validator. This http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx is a good example of how to write one in MVC3 using unobtrusive validation. It's for a custom datepicker but the same principle can be applied for your custom validation.