I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:
Related
I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}
I have created a partial view which takes one parameter on a form "email address", and I would like that string passed to my controller called "InviteTeam" which is decorated as an "HttpPost".
so here is the partial view and the ajax command
<form id="inviteTeam">
<label class="sr-only" for="communityCity">Team Email Address</label>
<input class="form-control" type="text" name="teamEmailAddress" id="teamEmailAddress" placeholder="Team Email">
Invite
</form>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
var formdata = $("#inviteTeam").serialize();
alert(formdata);
$.ajax({
type: "POST",
url: "/habitats/InviteTeam",
data: formdata,
success: function () {
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/"
},
error: function (errorData) { alert(errorData); }
})
});
});
</script>
and here is my controller code: my input string is "email" is null
public ActionResult InviteTeam()
{
return PartialView();
}
[HttpPost]
public ActionResult InviteTeam(string email)
{
return RedirectToAction("EditCommunity", "Habitats");
}
Change name="teamEmailAddress" to name="email" Try the following:
<form id="inviteTeam">
<label class="sr-only" for="communityCity">Team Email Address</label>
<input class="form-control" type="text" name="email" id="teamEmailAddress" placeholder="Team Email">
Invite
</form>
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
var formdata = $("#inviteTeam").serialize();
alert(formdata);
$.ajax({
type: "POST",
url: "/habitats/InviteTeam",
data: formdata,
success: function () {
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/"
},
error: function (errorData) { alert(errorData); }
})
});
});
</script>
Another solution is change the name of the parameter in your action method like:
[HttpPost]
public ActionResult InviteTeam(string teamEmailAddress)
{
return RedirectToAction("EditCommunity", "Habitats");
}
Also if you only want to redirect then you dont need any ajax call. You can simply redirect in javascript as:
window.location.href = "/Habitats/EditCommunity/"
But if you have to do some logic with your email address, then hit that controller action and return JSON as RedirectToAction will not work in AjaxCall like:
return Json("true");
In your success method of Ajax, you can check:
success: function (data) {
if (data == true){
$("#inviteModal").modal("hide");
window.location.href = "/Habitats/EditCommunity/";
}
}
when a submit button is clicked i want to generate a pop up showing the list of items. The code i tried to create pop up is as follows:`
Index View:
<script type="text/javascript">
$('#popUp').Hide();
$('#button').click(function () {
$('#popUp').click();
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm(FormMethod.Post))
{
<p>Search For: </p>
#Html.TextBox("companyName",Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
#Html.ActionLink("Get Company List", "CreateDialog", "Company", null, new
{
#class = "openDialog",
data_dialog_id = "emailDialog",
data_dialog_title = "Get Company List"
});
</div>
but i got trouble using this code.. when i click the submit button it opens another page instead of popup. The controller code is as follows:
[HttpPost]
public ActionResult Index(Companies c)
{
Queries q1 = new Queries(c.companyName);
if (Request.IsAjaxRequest())
return PartialView("_CreateDialog", q1);
else
return View("CreateDialog", q1);
}
You could use AJAX:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
$('#popUp').html(result);
}
});
return false;
});
});
</script>
<div class="left-panel-bar">
#using (Html.BeginForm())
{
<p>Search For: </p>
#Html.TextBox("companyName", Model);
<input id="button" type="submit" value="Submit" />
}
</div>
<div id="popUp">
</div>
Now ehn the form is submitted, an AJAX request will be sent to the Index POST action and since inside you test if the request was an AJAX request it will return the _CreateDialog.cshtml partial view and insert it into the #popUp div. Also it is important to return false from the form submit handler in order to cancel the default even which is to redirect the browser away from the current page.
System I working on is CMS where you insert templates like Contact form template and save that to database. This template is coded against server side to process data.
Now my "contentDiv" within form where all the templates were insert and saved than showed on the page withint form tag wrapped like
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
#Html.Hidden("someId", #Model.PageId)
}
<div id="contentDiv" style="width:100%">#Html.Raw(Model.Html)</div>
Above form is than saved as
$(function () {
$("form#first").submit(function (e) {
e.preventDefault();
var viewmodel = {
Id: $("#someId").val(),
Html: $("#contentDiv").val()
};
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: JSON.stringify(viewmodel),
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () { $("#status").fadeIn(); },
complete: function () { $("#status").fadeOut(); },
success: function (data) {
var message = data.Message;
},
error: function () {
}
});
});
});
notice that I moved "contentDiv out of form tag as my contact form which is wrapped in a form tag can not be nested within id=first form.
Is there a solution to form nesting? . If not than
My another question is
contentDiv is not wrapped up in form tag that means if client browser has javascript disabled than he wont be able to post contentDiv data to server and form will be of no use.
What to do?
If I don't move contentDiv out of form tag than than after inserting template the structure will be nesting of forms
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
<form id="contactform" action="/Home/Email" method="post" >
<div class="clear" style="padding-bottom:10px;"></div>
<div class="formCaption">Full Name</div>
<div class="formField"><input id="fullName" name="fullName" class="standardField" /></div>
<div><input id="sendBtn" value="Send" type="button" /></div>
</form>
}
I didn't understand from your description why the html needs to be outside the form. Also you should not use the .val() method for divs. You should use .html():
var viewmodel = {
Id: $("#someId").val(),
Html: $("#contentDiv").html()
};
Of course because you are using javascript to fetch the html which is outside of the main form if client browser has javascript disabled the form will be of no use. Only if you move the html inside the main form would this work without javascript:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
#Html.HiddenFor(x => x.PageId)
#Html.HiddenFor(x => x.Html)
<input type="submit" value="Edit" />
}
<!--
You could still keep the div for preview or something but don't make
any use of it when submitting.
-->
<div id="contentDiv" style="width:100%">
#Html.Raw(Model.Html)
</div>