I reached a point in my code where I need to call a method in the controller from the view.
I need to send some parameters with him from DropDownLists and TextBoxes.
I dont want to make a #using (Html.BeginForm... and an <input>, I just want to keep a <button> with a function call there that gathers that info and runs the method.
Is it possible?
An example of my DDL and Textbox:
#Html.DropDownListFor(cModel => cModel.QueueMonitorConfigTypeName, Enum.GetValues(typeof(BPM.Website.Models.PathType)).Cast<BPM.Website.Models.PathType>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = v.ToString()
}), new { id = "ddlConfigTypeName" })
#Html.TextBoxFor(cModel => cModel.Location, new { id = "txtbLocation" })
My button:
<button id="btnAddUpdateConfig" name="btnAddUpdateConfig" value="Apply" onclick="ValidateValues()">Apply</button>
JS:
function ValidateValues()
{
$.ajax({
type: "POST",
url: "Storage/AddUpdateConfigs",
data: ({id: #Model.QueueMonitorConfigurationsID, PathType: $('#ddlConfigTypeName').val(), Threshold:$('#ddlThreshold').val(), ValueType:$('#ddlValueTypeName').val(), Location: $('#txtbLocation').val(), Limit: $('#txtbLimit').val(), config: $('#NewOrUpdate').val() }),
dataType: JSON
});
}
But my function AddUpdate Configs is not being triggered:
public ActionResult AddUpdateConfigs(int id, string configType, string location, string threshold, string valueType, int limit)
{
return PartialView();
}
I put a breakpoint in the return and is not reached
Something like this should work:
$.postify = function(value) {
var result = {};
var buildResult = function(object, prefix) {
for (var key in object) {
var postKey = isFinite(key)
? (prefix != "" ? prefix : "") + "[" + key + "]"
: (prefix != "" ? prefix + "." : "") + key;
switch (typeof (object[key])) {
case "number": case "string": case "boolean":
result[postKey] = object[key];
break;
case "object":
if (object[key].toUTCString)
result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
else {
buildResult(object[key], postKey != "" ? postKey : key);
}
}
}
};
buildResult(value, "");
return result;
};
function login() {
var logonmodel = {
UserName: $tbUsername.val(),
Password: $tbPassword.val()
};
$.ajax({
type: "POST",
url: "/account/logon",
data: $.postify(logonmodel),
asynch: true,
dataType: "json",
success: function (msg) {
console.log(msg.state);
if (msg.state == 'good') {
window.location.href = msg.url;
}
else {
var $generalLoginError = $('span#generalLoginError');
var $loginuserNameError = $('span#loginUserNameError');
var $loginPasswordError = $('span#loginPasswordError');
$loginuserNameError.html(msg.errors.username);
$loginPasswordError.html(msg.errors.password);
if (msg.errors.incorrect != '')
$generalLoginError.html(msg.errors.incorrect);
}
}
});
}
Here's the controller action:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Json(new { url = returnUrl, message = "", state = "good" });
}
else
{
return Json(new { url = "/", message = "", state = "good" });
}
}
}
// If we got this far, something failed, redisplay form
return Json(new
{
url = "/",
errors = new
{
username = (model.UserName == null) ? "required" : "",
password = (model.Password == null) ? "required" : "",
incorrect = (!Membership.ValidateUser(model.UserName, model.Password)) ? "The user name or password provided is incorrect." : "",
//generic = "An error has occurred. If the error persists, please contact the webmaster."
},
state = "error"
});
}
Do an AJAX request when the button is clicked.
$.ajax({
type: "POST",
url: http://site.com/Controller/Action,
data: data,
success: success,
dataType: dataType
});
See:
http://api.jquery.com/jQuery.post/
Related
I want to populate #2 by using onchange event of #1 and using ajax to call action in controller but it returns 'undefined'.
I tried JsonResultBehavior.AllowGet but it is deprecated in asp.net core
VIEW:
<div class="col-md-4" style="padding-bottom: 1em;">
<label for="ddlCorporateName">Corporate Name
</label>
<select id="ddlCorporateName" class="form-control" required></select>
</div>
AJAX/jquery:
<script type = "text/javascript">
function GetSelectedStatus(ddlStatus) {
var id = ddlStatus.options[ddlStatus.selectedIndex].innerHTML;
var selectedValue = ddlStatus.value;
//window.location.href = '#Url.Action("PopulateCorporateName",
"POMultipleApprovalSummary") / ' + id;
$(function() {
var ddlCorporateName = $("#ddlCorporateName");
ddlCorporateName.empty().append('<option selected="selected"
value = "0"
disabled = "disabled" > Loading..... < /option>');
$.ajax({
type: "POST",
url: '#Url.Action("PopulateCorporateName", "POMultipleApprovalSummary") / ' + id,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(reponse) {
ddlCorporateName.empty().append('<option
selected = "selected"
value = "0" > Select All < /option>');
$.each(reponse, function() {
ddlCorporateName.append('<option selected="selected"
value = "' + this.CorporateName + '" > ' + this.CorporateName + '</option>');
});
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
});
}
</script>
CONTROLLER:
[HttpPost][Produces("application/json")]
public JsonResult PopulateCorporateName(string id) {
IPage page = new IPage(_accessor);
string status = id;
string accesslevel = string.Empty;
string CustName = string.Empty;
if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.BUHead) {
if (status == "Printed") {
accesslevel = "BU01PRINT";
} else if (status == "Pending SAM") {
accesslevel = "BU01";
} else if (status == "Pending Approval") {
accesslevel = "BU01PENDINGAPPROVAL";
} else if (status == "Approved SAM") {
accesslevel = "APPROVEDSAM";
} else if (status == "Rejected SAM") {
accesslevel = "REJECTEDSAM";
}
} else {
if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel3) {
accesslevel = "AP03";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel4) {
accesslevel = "AP04";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel2) {
accesslevel = "AP02";
} else if (page.UserPageAccessLevel == Models.Constant.UserAccessLevel.ApproverLevel5) {
accesslevel = "AP05";
}
if (status == "All Pending") {
accesslevel = accesslevel + "ALL";
} else if (status == "Pending Approval") {} else if (status == "Rejected SAM") {
accesslevel = "REJECTEDSAM";
} else if (status == "Approved SAM") {
accesslevel = "APPROVEDSAM";
}
}
try {
List < Models.POMultipleApprovalOverride > items2 = new
List < Models.POMultipleApprovalOverride > ();
Hashtable htParameters2 = new Hashtable();
htParameters2.Add("POMultipleGroup", "");
htParameters2.Add("AccessLevel", accesslevel);
htParameters2.Add("PONumber", "");
htParameters2.Add("CorporateName", "Select All");
items2 = (List < Models.POMultipleApprovalOverride > ) BusinessRules.Corporates.itemPOAppMultiple(htParameters2);
return Json(items2);
} catch(Exception e) {
return Json(e.Message);
}
}
I just wan to populate "CorporateName" element from the Items2 object.
This should work
$.each(reponse, function(index, corpInfo) {
ddlCorporateName.append('<option selected="selected"
value = "' + corpInfo.CorporateName + '" > ' + corpInfo.CorporateName + '</option>');
});
Hope this helps...
Receiving a '500 Internal Server Error' message when using ajax to call controller action in server with IIS 7.5 web site. Process works fine in localhost development environment.
The process involves an Ajax call that sends a json object to the controller action method which then sends back a json message. I've already tried creating a custom route in the Routeconfig file to take into account the iis site name. IE, "http://localhost:3000/home" vs "http://{SiteName}/{defaultapplicationpage}.
JS File
$.ajax({
async: false,
type: "POST",
url: "/TimeEntryWeeklyReportsTest/Home/CheckIfRecordsExist",
//url: "/Home/CheckIfRecordsExist",
data: '{ data:' + jsondata + '}',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (response) {
console.log(response);
if (response === "true") {
var param = "&StartDate=" + data.StartDate + "&EndDate=" + data.EndDate;
param = Employeefilter !== undefined ? param + "&" + Employeefilter + "=" + data.EmployeeUserid : param + "&Employee=" + data.EmployeeUserid;
$('#successmsg').html("Successful");
window.location.href = url + param + "&rs:Format=" + documentType;
}
else {
$('#errmsg').html("No records found.");
throw 'records not found error';
}
}).fail(function (response) {
console.log('Error: ' + response);
});
CS Controller
[HttpPost]
[Route("TimeEntryWeeklyReportsTest/Home/CheckIfRecordsExist")]
public JsonResult CheckIfRecordsExist(FormData data)
{
string strID = GetIDFromUser((!String.IsNullOrEmpty(GetUser())) ? GetUser() : Environment.UserName);
var results = timeEntry.TimeEntryReport(data.EmployeeSupervisor == "Supervisor" ? null : data.EmployeeUserid, data.EmployeeSupervisor == "Employee" ? null : data.EmployeeUserid, Convert.ToDateTime(data.Startdate), Convert.ToDateTime(data.Enddate)).ToList<TimeEntryReport_Result>();
if (results.Count != 0)
{
return Json("true", JsonRequestBehavior.AllowGet);
}
else
{
return Json("false", JsonRequestBehavior.AllowGet);
}
}
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "CheckIfRecordsExist",
url: "TimeEntryWeeklyReportsTest/{controller}/{action}",
defaults: new { controller = "Home", action = "CheckIfRecordsExist" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
The expected Result is to have the method return either a "true" or "false" statement. It seems that the ajax call is not handled and a 500 internal error is received.
Try in your controller like this to serv json and used that in javascript
public async Task<JsonResult> DonutChartData()
{
int tagIn = (await db.Tag.Where(x => x.IsIn == true).ToListAsync()).Count;
int cardIn = (await db.Entry.Where(c => c.Type == Type.Card).Where(x => x.IsExit == false).ToListAsync()).Count;
int reservedIn = (await db.Cars.Where(c => c.Type == Type.Pin).Where(x => x.IsExit == false).ToListAsync()).Count;
DonutChart _chart = new DonutChart();
_chart.labels = new string[] { "x", "y", "x" };
_chart.datasets = new List<DonutChartDatasets>();
List<DonutChartDatasets> _dataSet = new List<DonutChartDatasets>();
_dataSet.Add(new DonutChartDatasets()
{
label = "Whois",
//TO-DO: Add Reserve to Report
data = new int[] { cardIn, tagIn, reservedIn },
backgroundColor = new string[] { "rgba(54, 162, 235,0.5)", "rgba(255, 205, 86,0.5)", "rgba(255,99,132,0.5)" },
borderColor = new string[] { "rgb(54, 162, 235)", "rgb(255, 205, 86)", "rgb(255,99,132)" },
borderWidth = "1"
});
_chart.datasets = _dataSet;
return Json(_chart, JsonRequestBehavior.AllowGet);
}
And in your view script used data in this way:
jQuery.extend({
getValues: function (url) {
var result = null;
$.ajax({
url: url,
type: 'get',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
result = data;
}
});
return result;
}
});
I have an appointments application with multiple users who can multiple appointments. I display this on FullCalendar.
However, I'm having a problem. I want the User logged in to see their events and not others. This works when I close the application completely but if I log out and want to login as another user, I see the other users appointments.
I tried using re fetch events with FullCalendar then I looked at the Configuration.ProxyCreationEnabled = false; within my DAL class.
Here's my controller method:
public JsonResult GetEvents()
{
string username = Membership.GetUser().UserName;
var getAdmin = (from a in db.Admins
where username == a.AdminUsername
select a.AdministrationId).SingleOrDefault();
var events = (from a in db.Appointments
where getAdmin == a.AdministrationId
select a).ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
And FullCalendar:
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Appointments/GetEvents",
success: function (data) {
$.each(data, function (i, v) {
events.push({
details: v.DetailsOfAppointment,
date: moment(v.DateOfAppointment),
room: v.RoomType,
confirmed: v.Confirmed,
colour: v.ThemeColour,
church: v.Church.Name,
parishAdminName: v.Admins.AdministratorName,
parishAdminUser: v.Admins.AdminUsername,
parishAdminId: v.Admins.AdministratorId,
fee: v.Fee,
id: v.AppointmentId
});
})
GenerateCalender(events);
},
error: function (error) {
alert("failed");
console.log(error);
}
})
function GenerateCalender(events) {
$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar('refetchEvents');
$('#calender').fullCalendar({
contentHeight: 500,
defaultDate: new Date(),
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
timeFormat: 'HH:mm',
eventLimit: true,
eventColor: events.ThemeColour,
events: events,
eventRender: function (event, element) {
if (event.fee == null) {
if (event.confirmed == false) {
element.css('background-color', '#FF0000');
element.css('border-color', '#FF0000');
}
else {
element.css('background-color', '#008000');
element.css('border-color', '#008000');
}
}
else
{
element.css('background-color', '#0000FF');
element.css('border-color', '#0000FF');
}
},
eventClick: function (calEvent, jsEvent, view) {
$('#myModal #details').text(calEvent.details);
var $details = $('<div/>');
if (calEvent.fee != null) {
$details.append($('<p/>').html('<b>Date of Ceremony : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
else {
$details.append($('<p/>').html('<b>Date of Appointment : </b>' + calEvent.date.format("DD-MMM-YYYY HH:mm a")));
}
if (calEvent.end != null) {
$details.append($('<p/>').html('<b>End:</b>' + calEvent.end.format("DD-MMM-YYYY HH:mm a")));
}
$details.append($('<p/>').html('<b>Details : </b>' + calEvent.details));
$details.append($('<p/>').html('<b>Church Name : </b>' + calEvent.church));
if (calEvent.fee == null) {
if (calEvent.room != null) {
$details.append($('<p/>').html('<b>Room : </b>' + calEvent.room));
}
else {
$details.append($('<p/>').html('<b>Room Not Confirmed'));
}
}
$details.append($('<p/>').html('<b>Parish Admin : </b>' + calEvent.parishAdminName));
if (calEvent.confirmed == true)
{
$details.append($('<p/>').html('<b>Status : Confirmed </b>'));
}
else
{
$details.append($('<p/>').html('<b>Status : Not Confirmed </b>'));
}
$('#myModal #pDetails').empty().html($details);
$('#myModal').modal();
}
})
}
})
</script>
}
Your JSON payload is likely being cached by the browser.
To stop this, add this attribute above GetEvents:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = OutputCacheLocation.None)]
to disable caching.
On my View I have a button I use to submit a [description] value to my Controller via JSON, which is then used to create a new Table record. For example:
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
}
What I'd like to do now (before saving the Status to the DB) is run a check to see if any other records in the INV_Statuses table have a [description] value matching the one submitted to the function for new creation. If there is a match, I want to return an error/validation? message and alert the user the submitted value already exists and to choose it from the DropDownList on the View.
Can anyone provide an example of how to go about this with LINQ in my MVC Controller?
EDIT: Added my View JS code for submitting the new Status:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
EDIT2:
Adricadar's suggestion:
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
if (isDuplicateDescription)
{
ModelState.AddModelError("Error", "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.");
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description }, JsonRequestBehavior.AllowGet);
I added a .ToUpper() in my comparison in Controller, but even though the match with .ToUpper() gets identified, the ModelState.AddModelError() code fires, then the code returns and no error message is issued?
The value (though duplicate) still gets added to the dropdownlist (visually, not in DB) via my current JS code:
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
},
error: function () {
alert("ERROR!");
}
});
});
Check for existing status and set status back as follows:
var existingStatus = db.INV_Statuses.FirstOrDefault(s => s.status_description == description);
if (existingStatus ==null)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
else
{
// set the status back to existing
status = existingStatus;
}
Set an existing flag in your response:
return Json(new { ID = status.Id, Text = status.status_description, AlreadyExists = (existingStatus != null) }, JsonRequestBehavior.AllowGet);
Then in your response JavaScript, simply parse out the returned data:
success: function (resp) {
if (resp.AlreadyExists != true)
{
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
else
{
alert(resp.status_description + " already exists");
$("#selectStatus").val(resp.Id);
}
}
You can query the database for a status with an existing description and if exists and an model state error.
Be aware that string comparison is case sensitive.
[HttpPost]
public JsonResult createNewStatus(string description)
{
INV_Statuses status = new INV_Statuses()
{
// ID auto-set during save
status_description = description,
created_date = DateTime.Now,
created_by = System.Environment.UserName
};
//var allErrors = ModelState.Values.SelectMany(x => x.Errors);
try
{
var existingStatus = db.INV_Statuses.FirstOrDefault(x => x.status_description.ToUpper() == status.status_description.ToUpper());
var isDuplicateDescription = existingStatus != null;
string error = String.Empty;
if (isDuplicateDescription)
{
error = "[" + status.status_description + "] already exists in the database. Please select from the DropDownList.";
}
else if (ModelState.IsValid)
{
db.INV_Statuses.Add(status);
db.SaveChanges();
}
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
return Json(new { ID = status.Id, Text = status.status_description, Error = error , IsDuplicate = isDuplicateDescription }, JsonRequestBehavior.AllowGet);
}
In javascript verify if response have IsDuplicate = true if is true you skip the part where you need to add an element in dropdown.
$('#createNewStatus').click(function () {
$('#createStatusFormContainer').show();
})
$('#cancelNewStatus').click(function () {
$('#createStatusFormContainer').hide();
})
$('#submitNewStatus').click(function () {
var form = $(this).closest('form');
var data = { description: document.getElementById('textNewStatus').value };
$.ajax({
type: "POST",
dataType: "JSON",
url: '#Url.Action("createNewStatus", "INV_Assets")',
data: data,
success: function (resp) {
if(resp.IsDuplicate)
{
//display error from response
//display resp.Error
} else {
$('#selectStatus').append($('<option></option>').val(resp.ID).text(resp.Text));
form[0].reset();
$('#createStatusFormContainer').hide();
var count = $('#selectStatus option').size();
$("#selectStatus").prop('selectedIndex', count - 1);
}
},
error: function () {
alert("ERROR!");
}
});
});
I am trying to update ClientInfo table. But it is not updating and shows that Undefined. Those code below i have used in my controller for updating my database table data. Where is my problem i cannot find out? experts please help me..
[HttpPost]
public JsonResult Update(ClientInfo clnt, int id)
{
if (ModelState.IsValid)
{
ClientInfo c = db.Query<ClientInfo>("Select * from ClientInfo Where CId=#0", id).First<ClientInfo>();
c.CName = clnt.CName;
c.CCName = clnt.CCName;
c.Address = clnt.Address;
c.PhoneNo = clnt.PhoneNo;
c.Fax = clnt.Fax;
c.Email = clnt.Email;
c.Country = clnt.Country;
c.PostalCode = clnt.PostalCode;
c.Update();
return Json(c, JsonRequestBehavior.AllowGet);
}
else
return Json(new { msg = "Fail to Update Client Info." + id });
}
And Search Controller For searching Data
public JsonResult Search2(string id=null)
{
if (id != null)
{
var sresult = db.Query<ClientInfo>("Where CId=" + id).ToList<ClientInfo>();
return Json(sresult, JsonRequestBehavior.AllowGet);
}
else
return null;
}
And my ajax call from views For searching data by cid value..
#section scripts{
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search2/" + v;
// alert("Test : " + url);
$("#CName").val("");
$("#CCName").val("");
$("#PhoneNo").val("");
$("#Fax").val("");
$("#Email").val("");
$("#Address").val("");
$("#PostalCode").val("");
$("#Country").val("");
$.getJSON(url, null, function (data, status) {
$.each(data, function (index, C) {
$("#CName").val(C.CName);
$("#CCName").val(C.CCName);
$("#PhoneNo").val(C.PhoneNo);
$("#Fax").val(C.Fax);
$("#Email").val(C.Email);
$("#Address").val(C.Address);
$("#PostalCode").val(C.PostalCode);
$("#Country").val(C.Country);
});
});
});
For database update i have used this function ...
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
});
});
</script>
}
If you mean Undefined in your alert message box, it's simple:
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
Your ajax code displays the content of data.msg. But when your model is valid, it retrieves the model from the database, updates it and returns the new model. There is no msg json property if it succeeds, hence data.msg is undefined.
If you want it to return a success message, you need to change
return Json(c, JsonRequestBehavior.AllowGet);
into
return Json(new { msg = "Update Successful.", record = c }, JsonRequestBehavior.AllowGet);
then you will have a message in data.msg and your newly updated record in data.record.
DBContext have a save method you must run this.
Did you run Save(); method ?