I am supposed to convert a form submission from MVC Razor submission to an Ajax submission but I am having trouble even using simple javascript functions in the view of the form (Add.cshtml).
For starters, I try to link the JS file that i want to use in the following way:
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
The javascript file looks like this:
function dosubmit() {
$("#add_address").ajaxForm({ url: '~/Home/Add', type: 'post' })
alert("IT WORKS");
return false;// if it's a link to prevent post
}
and I have my form built in the following way:
#model MvcApplicationTest.Models.PersonModel
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
#{
ViewBag.Title = "Hinzufügen";
}
<h2>Hinzufügen</h2>
<form id="add_address">
<div class="fieldrow">
#Html.LabelFor(x => x.Nachname)
#Html.TextBoxFor(x => x.Nachname)
#Html.ValidationMessageFor(x => x.Nachname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Vorname)
#Html.TextBoxFor(x => x.Vorname)
#Html.ValidationMessageFor(x => x.Vorname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Strasse)
#Html.TextBoxFor(x => x.Strasse)
#Html.ValidationMessageFor(x => x.Strasse)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Hausnummer)
#Html.TextBoxFor(x => x.Hausnummer)
#Html.ValidationMessageFor(x => x.Hausnummer)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Plz)
#Html.TextBoxFor(x => x.Plz)
#Html.ValidationMessageFor(x => x.Plz)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Ort)
#Html.TextBoxFor(x => x.Ort)
#Html.ValidationMessageFor(x => x.Ort)
</div>
<!--Martin-->
<div class="fieldrow">
#Html.LabelFor(x => x.Email)
#Html.TextBoxFor(x => x.Email)
#Html.ValidationMessageFor(x => x.Email)
</div>
<input type="button" onclick="dosubmit()" value="Speichern" />
</form>
However, when I click the button nothing happens (it should pop up a window with the desired text).
I have tried to include the JS file into the _Layout.cshtml, but it still doesn't work.
Thanks for your help :)
You should just need to call .ajaxForm on the form itself when the document is ready. .ajaxForm by itself just prepares the form for ajax submission, so by the time the submit button has been pressed, it's already too late.
I'd remove the submit handler from the submit button (I'd also use an input of type submit here):
<input type="submit" value="Speichern" />
and add the following:
$(function () {
$("#add_address").ajaxForm({
url: '~/Home/Add',
beforeSubmit: function () {
alert('about to submit');
},
type: 'post'
});
});
Alternatively you could use .ajaxSubmit instead of .ajaxForm:
function dosubmit() {
$("#add_address").ajaxSubmit({ url: '~/Home/Add', type: 'post' });
alert("IT WORKS");
return false;// if it's a link to prevent post
}
Related
For example, in my project I'm using #using(Html.BeginForm(some stuff))to create an instance of my model and finally appending it to my database. But, when I'm editing (updating) some object of model, I'm usingn ajax get to retrieve data and finally using #Html.BeginForm() to post the update. Well, this is breaking some pattern of coding in MVC or whatever good principle?
Retrieving data and filling in the input fields
$.ajax({
url: "../../Obra/" + id,
type: "POST",
success: function(data) {
var obj = JSON.parse(JSON.stringify(data));
tit.value = obj.titulo;
ed.value = obj.editora;
obj.autores.forEach(x => {
var newn = divAutor.appendChild(aut.cloneNode());
newn.value = x;
});
img.value = obj.imagem;
divAutor.removeChild(aut);
},
error: function() {
alert('Error.');
}
});
All modal:
<div class="modal" id="modalOverlay">
<div class="modal-content" id="modalContent">
<header class="modal-header">
<h1 id="updateObraModalTitulo"></h1>
</header>
#using(#Html.BeginForm("Update", "Obra", FormMethod.Post, new { id="form-update" })) {
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Titulo, "Título:")
#Html.TextBoxFor(m => m.Titulo, new { #class="editInputValue", #id="editTituloInput" })
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Editora, "Editora:")
#Html.TextBoxFor(m => m.Editora, new { #class="editInputValue", #id="editEditoraInput"})
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Autores, "Autores:")
<div id="divInputAutores">
#Html.TextBoxFor(m => m.Autores, new { #class="inputPostValue", id="addAutoresInput"})
</div>
<div class="btnNewAutorOp">
<button type="button" id="btnAddAutor" onclick="addNewAutor()">+</button>
<button type="button" id="btnDeleteAutor" onclick="deleteNewAutor()">×</button>
</div>
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Imagem, "Imagem:")
#Html.TextBoxFor(m => m.Imagem, new { #class="inputPostValue", #id="editImagemInput" })
</div>
<input type="submit">
}
</div>
</div>
Because I can't retrieve the Id property when I click in the modal with mvc (or maybe I can using partial views?), I'm using javascript to create a function with the param id and getting data with ajax and finally updating with form
I am a beginner in asp.net MVC.
I am using MVC 4 for my project and I am using strongly typed partial view and I render it in a View.
What I am trying to achieve is when a user enters a email address in Email Address textbox which is generated by #Html.EditorFor(model=>model.Email)
Html helper and when user looses focus on that textbox; a jQuery function
focusout will get called which will check if entered Email is already present in a database or not. Following is my code
#model PITCRoster.tblLoginDetail
#using (Html.BeginForm("AddUser","Resources",FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>tblLoginDetail</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model=>model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<p id="emailVerify"></p>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserPassword)
#Html.ValidationMessageFor(model => model.UserPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ConfirmPassword)
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and I have a jQuery function which is as follows
$("#Email").focusout(function () {
var emailData = $("#Email").val();
$.ajax({
url: '/Resources/CheckEmailAddress',
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
data: '{emailId:"' + emailData + '"}',
success: OnSuccess,
failure: function (data) {
alert('something went wrong!');
}
});
function OnSuccess(data) {
debugger;
if (!data) {
$("#emailVerify").css('color', 'green');
$("#emailVerify").html("Valid Email!");
}
if (data) {
$("#emailVerify").css('color', 'red');
$("#emailVerify").html("Email already registered!");
}
}
});
The jQuery function doesn't get called for the textbox created by Html Helper
But when I replace that Html helper with following code it runs properly.
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
<input type="email" class="text-box single-line" name="Email" value="" id="Email" data-val-required="The Email field is required." data-val-email="The Email field is not a valid e-mail address." data-val="true" />
#Html.ValidationMessageFor(model => model.Email)
</div>
CheckEmailAddress is a method in Resources controller.
Can anybody help me out why jQuery function doesn't get called when I use #Html.EditorFor(model=>model.Email)?
Assign an id and type to your model. By default it doesn't have an id of Email
#Html.TextBoxFor(x => x.Email, new {type="email", id="Email"})
I am creating an application on MVC Mobile and having a problem. Here i have a Partial view load on a page run-time by ajax. In which i have a simple form which will submit with ajax request like bellow:
#model Test.Models.TestModel
#using (this.Ajax.BeginForm("Create", "Test", Model, new AjaxOptions { UpdateTargetId = "divResult", LoadingElementId = "loading", LoadingElementDuration = 2000, HttpMethod = "Post" }, new { id = "frmCreate" }))
{
#Html.AntiForgeryToken()
<div class="messageBox">#Html.Raw(TempData["Message"])</div>
<div class="atmForm">
<div class="control-group">
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name, new { #placeholder = "Name", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Name)
</div>
<div class="control-group">
#Html.LabelFor(x => x.Notes)
#Html.TextAreaFor(x => x.Notes, new { #placeholder = "Notes", #class = "inputStyle" }) #Html.ValidationMessageFor(x => x.Notes)
</div>
</div>
<div class="form-actions2 clearfix">
<input type="submit" class="btn btn-block" value="Create" data-ajax="false" id="btnFormSubmit" />
</div>
}
<script type="text/javascript">
$.validator.unobtrusive.parse("#frmCreate");
</script>
The problem is when user submit the form the controller called twice. First time it return the partial view and then again it calls and then jQuery Mobile change the page. I am Using MVC4 with jQuery Mobile 1.1.0
(please note that create.cshtml (desktop ver) works fine but create.Mobile.cshtml (mobility ver) havng this problem)
Do not submit the form, use $("#myForm").serialize() as ajax data.
Im getting confused about the onfocusout event in my mvc view.
<div class="editor-field" id="supplieridentificationID" >
#Html.EditorFor(m => m.SupplierIdentification)
</div>
<div id="suppliername" class="editor-label" />
And my javascript code:
$('#supplieridentificationID').onfocusout(function () { alert("ajax here!" })
I cant get this to work, actually im trying to send the SupplierIdentification to my controller and get the Json with the SupplierName and put on "suppliername" label.
All using onfocusout function with the ajax.
Any sugestions?
EDIT:
I tried other code, and still not getting nothing:
<div>
<fieldset>
<legend>Novo Documento</legend>
<div class="editor-field" id="ident">
#Html.EditorFor(m => m.SupplierIdentification)
</div>
</fieldset>
</div>
And script:
<script type="text/javascript">
$(document).ready(function() {
$('#ident').focusin(function () { alert("focusin"); });
});
Use focusout instead of onfocusout
$('#SupplierIdentification').focusout(function() { alert("ajax here!" });
try adding an id to control so you can reference it in Jquery.
#Html.EditorFor(m => m.SupplierIdentification, new { #id = "id"})
$(document).ready(function() {
$('#id').blur(function () {
alert("focusin");
});
});
blur function happens when element loses focus
I have a partial view on my application I am creating user registration functionality on partial view(not using any form tag) , I am calling Controller's action method using ajax-jquery & passing user details(model) to action method , before calling ajax method i need to validate user detail at client side. how can i do this?
need to validate model before ajax call(not using any form tag).
#model MVC4Demo.Models.Student
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function onClientClick() {
var obj = { FirstName: "name", City: "abc" };
$.ajax({
url: "/Home/AjaxDemo",
data: JSON.stringify(obj),
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('success');
},
error: function () {
alert("error");
}
});
}
</script>
<div id="Main">
<label>Student</label>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</div>
<p>
<input type="submit" onclick="onClientClick()" value="Create" />
</p>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Put your model into form. After:
<script>
$(function () {
$('#myForm').unbind('submit');
$('#myForm')
.bind('submit', function () {
var form = this;
if ($("#myForm").valid()) {
$.post('/Home/AjaxDemo', $(form).serialize(), function (data) {
if (data.success) {
alert('success');
} else {
alert("error");
}
});
}
return false;
});
});
I'm afraid a form tag is required. And something else, you can prepend
#Html.EnableClientValidation();
#Html.ValidationSummary(true);
to the form.