When I try to send a variable to JSON on ASP.net MVC, I am getting error like below:
jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error)
My controller:
public JsonResult GetAddress(int uservalue, string email)
{
UserService rpuser = new UserService();
DATA.Models.ORM.Entity.UserEntity.User userentity = rpuser.FirstOrDefault(x => x.Id == uservalue);
Models.DTO.OrderDTO.NewAddressVM addressmodel = new Models.DTO.OrderDTO.NewAddressVM();
addressmodel.FirstName = userentity.Name;
return Json(addressmodel.FirstName, JsonRequestBehavior.AllowGet);
}
View:
<script>
$(document).ready(function () {
$("#okbutton").click(function () {
var e = document.getElementById("emailadd");
var uservalue = e.options[e.selectedIndex].value;
var usertext = e.options[e.selectedIndex].text;
var link = "/Order/GetAddress/";
$.ajax({
type: "GET",
url: link,
data: {userid: uservalue, email: usertext},
success: function (result) {
if (result == "accept") {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />If you complete your order you will get a discount of £50.</span>');
} else {
$("div#voucher-result").html('<span style="color:green; font-weight:bold;">Your voucher code is valid. Discount price: <text style="font-size:19px;">£50</text><br />Else</span>');
}
}
});
});
});
And Form:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Customer</label>
#Html.DropDownListFor(x => x.CustomerId, new SelectList(Model.CustomerList, "Id", "UserName"), new { #class = "form-control select2", #id="emailadd", #placeholder = "" })
</div>
</div>
<div class="col-md-6">
<label></label>
<button type="button" class="btn btn-block btn-success" id="okbutton" style="width:60px;">OK</button>
</div>
<div id="voucher-result"></div>
</div>
GetAddress(int uservalue, string email) expects a parameter called uservalue but in your javascript you are sending over an userid: data: {userid: uservalue, email: usertext}
You should change the parameter uservalue to userid in your controller or change userid to uservalue in your javascript.
Related
The client-side validation in ASP.Net Core is not working. I have the following code:
#model VeoScheduling.Models.SignInModel
#{
ViewData["Title"] = "SignIn";
}
<div class="login">
<h2>Sign In</h2>
<div>
<form method="post" asp-action="SignIn">
<input type="hidden" asp-for="RedirectUrl" />
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input type="email"
data-bind="value: email" asp-for="Email"
class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"
class="control-label"></label>
<input type="password" asp-for="Password"
data-bind="value: password"
class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Account</label>
<select name="accountSelected" style="margin:5px;width:200px"
data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>
</div>
<br />
#if (Model.Error != "" || Model.Error != null)
{
<p style="color:red">#Html.Raw(Model.Error)</p>
}
</form>
</div>
</div>
#section Scripts{
<script>
var vModel = #Html.Raw(Json.Serialize(Model))
</script>
<script src="~/js/signIn.js" asp-append-version="true"></script>
}
I have also added javascript validation files and I can see they are being loaded when I run but still client-side validation is not working.
I have applied required attribute for both email and password filed. But client-side validation is still not working.
public class SignInModel
{
[Required(ErrorMessage ="Email is required")]
public string Email { get; set; }
[Required(ErrorMessage ="Password is required")]
public string Password { get; set; }
[DisplayName("Forgot Password")]
public bool ForgotPassword { get; set; }
public string RedirectUrl { get; set; }
public string Error { get; set; }
}
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
Below is the js code.
var viewModel = function (model) {
var self = this;
//properties
self.email = ko.observable('');
self.password = ko.observable('');
self.redirectUrl = model.redirectUrl;
self.availableAccounts = ko.observableArray(model.availableAccounts);
self.selectedAccount = ko.observable(null);
//events
self.signOn = function () {
var payloadData = {
'email': self.email(),
'password': self.password(),
'accountSelected': self.selectedAccount()
};
var url = window.location.origin + '/account/SignIn';
CallService("Post", url, payloadData)
.done(function (data) {
var url = window.location.origin + self.redirectUrl;
window.location.replace(url);
});
};
self.accountSelected = function (e, d) {
//alert(self.selectedStack());
};
//methods
self.forgotPassword = ko.observable(false);
self.resetPassword = function () {
$('#loader').show();
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/resetPassword'
$.post(url, payloadData)
.always(function () {
$('#loader').hide();
})
.fail(function (xhr, status, error) {
alert('resetPassword(): error' + xhr.responseText);
})
.done(function (data) {
alert("reset email sent.");
});
};
//ajax
self.getUsersAccounts = function () {
if (self.email() === "")
return;
var payloadData = {
'email': self.email()
};
var url = window.location.origin + '/API/GetAccountsByEmail';
CallService("GET", url, payloadData)
.done(function (data) {
self.availableAccounts.removeAll();
self.availableAccounts(data);
});
};
//computed
self.userChanged = ko.computed(function () {
var userID = self.email();
//alert(userID);
//console.log(userID);
self.getUsersAccounts();
});
self.forgotChecked = ko.computed(function () {
var checked = self.forgotPassword();
var email = self.email();
if (checked) {
if (email === '') {
alert("Please fill in email to reset password");
self.forgotPassword(false);
}
else {
alert("An email link will be sent to your email address.");
self.resetPassword();
self.forgotPassword(false);
}
}
});
//init
if (model.availableAccounts.length === 1) {
self.selectedAccount(model.availableAccounts[0].key);
}
};
$(document).ready(function () {
self.vm = new viewModel(self.vModel);
ko.applyBindings(self.vm);
});
you could try:
<form id="someform">
......
</form>
<script>
.....
if ($("#someform").valid())
{
//ajax codes
}
else {
return false;
}
</script>
also you could try:
var somevalue = document.getElementById("someId").value;
if (somevalue == null || somevalue == '')
{
$('#somespanId').html("*required");
return false;
}
The problem:
I am trying to save events in a calendar by passing the content in ajax to my controller function. But I keep on getting null values being passed to my database. I have checked the console.log under Network tools in browsers and all of the data is null except EventId .
I know inserting the events into the database is working but it seems like the data being inserted is not being read by either Ajax or there's something wrong with my controller. Why do I keep on getting null values?
What the data in my database looks like after I saved the events
Here's my controller
[HttpPost]
public IActionResult SaveEvent(Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
db.Events.Add(data);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}
This is my Event class:
public class Event {
public string UserId { get; set; }
public int? EventId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string EventStart { get; set; }
public string EventEnd { get; set; }
public string Counselor { get; set; }
public string ThemeColor { get; set; }
public bool AllDay { get; set; }
}
and my Ajax function
function GenerateCalender(events) {
jq341('#calender').fullCalendar('destroy');
jq341('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: events,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
jq341('#myModal #eventTitle').text(calEvent.title);
var description = jq341('<div />');
description.append(jq341('<p />').html('<b>Start:</b>' + calEvent.start.format("DD-MMM-YYYY HH:mm a")));
if (calEvent.end != null) {
description.append(jq341('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
description.append(jq341('<p />').html('<b>Description:</b>' + calEvent.description));
jq341('#myModal #pDetails').empty().html(description);
jq341('#myModal').modal();
},
selectable: true,
select: function (start, end) {
selectedEvent = {
userID: '',
eventID: 0,
title: '',
counselor: '',
start: start,
end: end,
description: '',
allDay: false,
color: ''
};
openAddEditForm();
jq341('#calendar').fullCalendar('unselect');
},
editable: true,
eventDrop: function (event) {
var data = {
UserId: event.userID,
EventId: event.eventID,
Title: event.title,
Counselor: event.counselor,
EventStart: event.start.format('DD/MM/YYYY HH:mm A'),
EventEnd: event.end != null ? event.end.format('DD/MM/YYYY HH:mm A') : null,
Description: event.description,
AllDay: event.allDay,
ThemeColor: event.color,
};
SaveEvent(data);
}
})
}
function openAddEditForm() {
if (selectedEvent != null) {
jq341('#hdEventID').val(selectedEvent.eventID);
jq341('#hdUserID').val(selectedEvent.userID);
jq341('#txtSubject').val(selectedEvent.title);
jq341('#ddCounselor').val(selectedEvent.counselor);
jq341('#txtStart').val(selectedEvent.start.format('DD/MM/YYYY HH:mm A'));
jq341('#chkIsFullDay').prop("checked", selectedEvent.allDay || false);
jq341('#chkIsFullDay').change();
jq341('#txtEnd').val(selectedEvent.end != null ? selectedEvent.end.format('DD/MM/YYYY HH:mm A') : '');
jq341('#txtDescription').val(selectedEvent.description);
jq341('#ddThemeColor').val(selectedEvent.color);
}
jq341('#myModal').modal('hide');
jq341('#myModalSave').modal();
}
jq341('#btnSave').click(function () {
//Validation
if (jq341('#txtSubject').val().trim() == "") {
alert('Title required');
return;
}
if (jq341('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if (jq341('#chkIsFullDay').is(':checked') == false && jq341('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var format_start = jq341('#txtStart').val().replace(' ', '-').split('-');
var nowy_start = format_start[1] + '-' + format_start[0] + '-' + format_start[2] + ' ' + format_start[3];
var format_end = jq341('#txtEnd').val().replace(' ', '-').split('-');
var nowy_end = format_end[1] + '-' + format_end[0] + '-' + format_end[2] + ' ' + format_end[3];
}
//edited
var data = {
UserId: jq341('#hdUserID').val(),
EventId: jq341('#hdEventID').val(),
Title: jq341('#txtSubject').val().trim(),
Counselor: jq341('#ddCounselor').val(),
EventStart: jq341('#txtStart').val().trim(),
EventEnd: jq341('#chkIsFullDay').is(':checked') ? null : jq341('#txtEnd').val().trim(),
Description: jq341('#txtDescription').val(),
ThemeColor: jq341('#ddThemeColor').val(),
AllDay: jq341('#chkIsFullDay').is(':checked')
}
alert(data);
SaveEvent(data);
// call function for submit data to the server
})
function SaveEvent(data) {
jq341.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
url: '/Calendar/SaveEvent',
data: JSON.stringify(data),
success: function (data) {
console.log(data)
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
jq341('#myModalSave').modal('hide');
}
},
error: function () {
alert('Failed', ErrorMessage);
}
})
}
my cshtml
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Appointments</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="text" id="hdEventID" value="0" />
<input type="hidden" id="hdUserID">
<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>
<div class="form-group">
<label>Counselor</label>
<select id="ddCounselor" class="form-control">
<option value="0">Choose your counselor</option>
<option value="DrSalwa">Dr Salwa</option>
<option value="DrNorzaiham">Dr Norzaiham</option>
<option value="Nasri">Sir Nasri</option>
<option value="Adibah">Ms. Adibah</option>
</select>
</div>
<div class="form-group">
<label>Start</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>
<div class="form-group" id="divEndDate" style="display:none">
<label>End</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
Below are screenshots of the Network tool
Using [FormBody] but getting that null exception in if(data.eventId >0) in controller
Below is [FormBody] is omitted from the controller but still getting null values except EventId
First, you should add the [FromBody] attribute, otherwise the data will not be successfully obtained.
You can add a breakpoint in your action to observe whether the binding is successful.
Then, modify your db.Add() method, because your data contains EventId, and in your database I see EventId as the primary key, and your primary key is auto-incremented. If you add a New entity of EventId, then an exception will be thrown.
You can try change your action like below:
[HttpPost]
public IActionResult SaveEvent([FromBody]Event data)
{
var userId = _userManager.GetUserId(User);
var status = false;
if (string.IsNullOrEmpty(userId))
{
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { Data = false, ErrorMessage = "no User Id!" });
}
if (data.EventId > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventId == data.EventId).FirstOrDefault();
if (v != null)
{
userId = data.UserId;
v.EventId = data.EventId;
v.Title = data.Title;
v.Counselor = data.Counselor;
v.Description = data.Description;
v.EventStart = data.EventStart;
v.EventEnd = data.EventEnd;
v.AllDay = data.AllDay;
v.ThemeColor = data.ThemeColor;
}
}
else
{
var data1 = new Event
{
UserId=data.UserId,
Title = data.Title,
Counselor = data.Counselor,
Description = data.Description,
EventStart = data.EventStart,
EventEnd = data.EventEnd,
AllDay = data.AllDay,
ThemeColor = data.ThemeColor,
};
db.Events.Add(data1);
}
db.SaveChanges();
status = true;
return Json(new { Data = data, status});
}
I can easily show/hide a <div> based on this View code:
<div class="form-group">
#Html.LabelFor(m => m.countryID, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.countryID, ((IEnumerable<Corporate.Models.Country>) ViewBag.Possiblecountries).OrderBy(c => c.countryName).Select(option => new SelectListItem
{
Text = Html.DisplayTextFor(_ => option.countryName).ToString(),
Value = option.countryID.ToString(CultureInfo.InvariantCulture),
Selected = (Model != null) && (option.countryID == Model.countryID)
}), new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.countryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" id="vatNumberDiv">
#Html.LabelFor(m => m.vatNumber, new {#class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.vatNumber, new {#class = "form-control"})
#Html.ValidationMessageFor(m => m.vatNumber, "", new {#class = "text-danger"})
</div>
</div>
and based on this Script:
<script type="text/javascript">
$(function () {
$('#countryID').change(function () {
var value = $(this).val();
if (value == 'FRA') {
$('#vatNumberDiv').show();
} else {
$('#vatNumberDiv').hide();
}
});
});
</script>
but what about checking all the EU members? I have a method called bool IsMemberEU() that requires MVC context to execute. Can I call it inside the script?
Maybe it's better to generate by code all the options inside the script? Something like:
if (value == 'FRA' ||
value == 'DEU' ||
value == 'ITA' ||
...
...
) {
Do I have some other option?
Thanks.
EDIT:
This is the code I need, to check if the country is EU member:
foreach(Country c in context.Countries)
{
if (IsMemberEU(c))
{
// is EU memeber
}
}
EDIT2: For M12 Bennet
<script type="text/javascript">
// $(function () {
$(document).ready(function() {
$('#countryID').change(function () {
// get selected option to submit to method IsMemberEU
var selectedOption = $(this).val();
// create URL for ajax call
var ajaxUrl = '#Url.Action("IsMemberEU", "Customers")';
$.ajax({
url: ajaxUrl,
data: { countryAbbv: selectedOption },
success: function(result) {
if (result) {
$("#vatNumberDiv").show();
} else {
$("#vatNumberDiv").hide();
}
// show result of ajax call in the `p` element on page. This is just testing to see if ajax call worked.
// this can be done with console.log(result) as well.
$("#ShowResult").text(result);
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
});
</script>
In a controller, you could create the method IsMemberEU(string countryAbbv). It needs to accept a parameter because you're checking against what you're sending to the method. So your code could look like this:
Controller Method
public bool IsMemberEU(string countryAbbv)
{
var lstCountries = db.Countries.Where(x => x.isEU).Select(t => t.Abbr).ToList();
return lstCountries.Contains(countryAbbv);
}
Then on your Razor/HTML page:
Razor/HTML
<div>
<select id="CountrySelect" name="countryAbbv">
<option value="">-- Select Country --</option>
<option value="FRA">FRA</option>
<option value="DEU">DEU</option>
<option value="ITA">ITA</option>
<option value="USA">USA</option>
</select>
<p id="ShowResult"></p>
</div>
Then in your jQuery to include AJAX:
jQuery/AJAX
<script>
$(document).ready(function() {
// create event listener for change of select
$("#CountrySelect").change(function() {
// get selected option to submit to method IsMemberEU
var selectedOption = $(this).val();
// create URL for ajax call
var ajaxUrl = '#Url.Action("IsMemberEU", "Home")';
$.ajax({
url: ajaxUrl,
data: { countryAbbv: selectedOption },
success: function(result) {
if (result)
$("#vatNumberDiv").show();
else
$("#vatNumberDiv").hide();
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
});
</script>
This is working as expected on my end. Now, this is just a basic example that I created myself based off of the information that was provided in the question. You shouldn't have to worry about the HTML/Razor that I provided because you're using Razor syntax.
I'm having a basic form with few text fields and a file upload controller on a bootstrap modal dialog (Bootstrap 4). below is my code:
Model:
public class DemoContent
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[RegularExpression("([0-9]+)",ErrorMessage = "Age must be numbers only")]
public int Age { get; set; }
[EmailAddress]
public string Email { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Image")]
public HttpPostedFileBase ImageUrl { get; set; }
}
JavaScript
$(function() {
$("a[data-modal=demoPopup]").on("click", function () {
$("#demoModalContent").load(this.href, function () {
$("#demoModal").modal({ keyboard: true }, "show");
$("#demoForm").submit(function () {
if ($("#demoForm").valid()) {
var files = $("ImageUrl").get(0).files;
var data = $(this).serialize();
data.append("ImageUrl", files[0]);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$("#demoModal").modal("hide");
location.reload();
} else {
$("#MessageToClient").text(result.message);
}
},
error: function () {
$("#MessageToClient").text("The web server had an error.");
}
});
return false;
}
});
});
return false;
});
Controller:
[HttpPost]
public ActionResult Create(DemoContent model)
{
if (model.Age > 55)
{
var file = model.ImageUrl;
return Json(new { success = true });
}
else
{
return Json(new { success = false,message="Invalid Data" });
}
}
Now when i open the popup it works also when i submit the form it goes to the controller along with the file. but the problem is once the server returns the success message the popup shows that message in a blank page instead of capturing it and refreshing the current page or showing the messages. any idea why is this happening.
link to source files : https://drive.google.com/open?id=1W3H3kFEpHJWfaf7_UnJI3O5I900GxyC7
May be you wrote your javascripts function in document.ready() function,That is why it again refreshing.
Write your JavaScript code as follows:
$(function() {
$("a[data-modal=demoPopup]").on("click", function () {
$("#demoModalContent").load(this.href, function () {
$("#demoModal").modal({ keyboard: true }, "show");
$("#demoForm").submit(function (event) { // Pass the event as parameter to the function.
event.preventDefault(); // I have added these two lines
event.stopImmediatePropagation();
if ($("#demoForm").valid()) {
var files = $("ImageUrl").get(0).files;
var data = $(this).serialize();
data.append("ImageUrl", files[0]);
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$("#demoModal").modal("hide");
location.reload();
} else {
$("#MessageToClient").text(result.message);
}
},
error: function () {
$("#MessageToClient").text("The web server had an error.");
}
});
return false;
}
});
});
return false;
});
I think you should install and use Microsoft.Unobtrusive.Validation and *.Ajax, if you want your modal to be updated (I get your question like that...). With this, you can use code like the following example, which can update your modal (used this in a project a few days ago):
Modal:
#using (Ajax.BeginForm("Login", new { Controller = "Home", area = "" }, new AjaxOptions() { OnSuccess = "onSuccessLogin", HttpMethod = "POST", UpdateTargetId = "loginmodalbody"}, new { id = "loginForm" }))
{
<div class="modal-body" id="loginmodalbody">
<div class="text-danger loginfailed"></div>
<div class="container">
<div class="card border-primary mb-3" style="margin: 0 auto;">
<div class="card-body">
#Html.Partial("~/Views/Shared/Modals/LoginModalBody.cshtml")
</div>
</div>
<div class="container">
<span><a onclick="alert('Leads to pw info')" href="#">Forgot password?</a></span>
</div>
<br />
<button class="btn btn-primary btn-block buttonlogin">Login</button>
</div>
<br />
</div>
}
Modal Body:
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-lg-12 col-12">
#Html.EditorFor(model => model.EMail, new { htmlAttributes = new { #class = "form-control", placeholder = "EMail", #id = "inputemail" } })
#Html.ValidationMessageFor(model => model.EMail, "", new { #class = "text-danger", #id = "dangeremail" })
</div>
</div>
<div class="form-group">
<div class="col-lg-12 col-12">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", placeholder = "Passwort", #id = "inputpassword" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger", #id = "dangerpassword" })
</div>
</div>
</div>
Thus, it updates your modal body after getting data from the posting of the form - you define the id to be updated within the AjaxOptions, as shown in the above snippet.
I have a Room record in my database and I want to edit it using a JsonResult Edit method in RoomController like this:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Edit(RoomViewModel roomViewModel)
{
if (roomViewModel == null) throw new ArgumentNullException(nameof(roomViewModel));
try
{
var apartmentRoomViewModel = new ApartmentRoomViewModel
{
Id = _entities.ApartmentRoom.Where(x => x.RoomID == roomViewModel.Id).Select(x => x.Id).Single(),
ApartmentID = _entities.ApartmentRoom.Where(x => x.RoomID == roomViewModel.Id).Select(x => x.ApartmentID).Single(),
RoomID = roomViewModel.Id
};
apartmentRoomViewModel.ApartmentID = roomViewModel.SelectedApartmentID;
var apartmentRoom = AutoMapper.Mapper.Map<ApartmentRoom>(apartmentRoomViewModel);
_entities.ApartmentRoom.AddOrUpdate(apartmentRoom);
_entities.SaveChanges();
var room = AutoMapper.Mapper.Map<Room>(roomViewModel);
var status = _roomRepository.Update(room);
_roomRepository.Save();
return Json(new { status, message = "Success!", url = Url.Action("List", "Room") });
}
catch
{
return Json(new { status = false, message = "Error!" });
}
}
After the method works, edit is successful but I cannot redirect the page to /Room/List. Instead, I am encountering a page like this:
My Script
<script type="text/javascript">
$(document).ready(function () {
$("#RoomEdit").click(function (e) {
e.preventDefault();
var data = {
DoorNumber: $("#DoorNumber").val(),
FloorNumber: $("#FloorNumber").val(),
Capacity: $("#Capacity").val(),
SelectedApartmentID: $("#SelectedApartmentID option:selected").val()
}
$.ajax({
type: "POST",
url: '#Url.Action("Edit","Room")',
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json",
success: function (result) {
if (result.status) {
window.location.href = result.url;
}
},
error: function () {
}
});
return false;
});
});
Edit.cshtml
<div class="row">
<div class="col-md-10 offset-md-1">
<div class="box">
<div class="box-header">
<h2>#ViewBag.Title</h2>
</div>
<div class="box-divider m-a-0"></div>
<div class="box-body">
#using (Html.BeginForm("Edit", "Room", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group row">
#Html.LabelFor(x => x.DoorNumber, new { #class = "col-sm-2 form-control-label" })
<div class="col-sm-10">
#Html.TextBoxFor(x => x.DoorNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.DoorNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(x => x.FloorNumber, new { #class = "col-sm-2 form-control-label" })
<div class="col-sm-10">
#Html.TextBoxFor(x => x.FloorNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.FloorNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(x => x.Capacity, new { #class = "col-sm-2 form-control-label" })
<div class="col-sm-10">
#Html.TextBoxFor(x => x.Capacity, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.Capacity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(x => x.ApartmentName, new { #class = "col-sm-2 form-control-label" })
<div class="col-sm-10">
#Html.DropDownListFor(x => x.SelectedApartmentID, Model.ApartmentList, new { #class = "form-control", id = "SelectedApartmentID" })
</div>
</div>
<div class="form-group row m-t-md">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="RoomEdit" class="btn green">Düzenle</button>
</div>
</div>
}
</div>
</div>
</div>
I couldn't understand what is wrong with my code. Any help will be appreciated.
Make your Button first with type="Button" instead of Submit, also change the click function id from btnAdd to btnEdit.
At server side, roomViewModel.Id will be getting 0 if you using old method, instead of this do serialize so you can get all the Inputs at server side method.
Also use, #Html.HiddenFor(x => x.id) to pass the Id to Method.
Try this function so you can call your Method with AJAX,
<script type="text/javascript">
$(document).ready(function () {
$("#RoomEdit").click(function (e) {
e.preventDefault();
var data = $("#formName").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Edit", "Room")',
data: data,
success: function (result) {
if (result.status) {
alert(result.message);
setTimeout(function () {
window.location.href = result.url;
}, 1000);
}
}
});
});
})
</script>
You have code to do ajax submit. But from the image you shared, it looks like it is doing a normal form submit. Make sure that you are preventing the default form submit behavior when the button is clicked.
You already have return false; which should do it.
It should work as long as you do not have other script errors in the page. (you can verify this by opening up the browser console)
Also make sure that you are returning true as the value of status property of the json data you are returning. There is no need to specify JsonRequestBehavior.AllowGet enum in the Json method overload when you are returning from an HttpPost action method. It is needed if your action method is HttpGet
return Json(new { status= true, message = "Success!", url = Url.Action("List", "Room") });
Also, it does not make any sense to have the $.notify call after you redirect to the new page. That means that call will not be executed at all!