I am working on MVC4 application in that this is Actionresult returns json result but i want to pass variable objservice.callid on view but i am returning json can it is possible to get value on view with the help of json result or having any method to pass the value of variable to view but return type shoould be json result.
Here is code in controller:
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
ViewBag.id = objservice.callID;
return Json("Service Call = " + objservice.callID + " is Created successfully!");
} else {
return Json("This record is not added because of this error:=>" + result);
}
}
Here is code in view:
if (str.indexOf("successfully") != -1)
{
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", '#ViewBag.id');
} else {
if (str.search("added") != -1)
{
window.location.href = '#Url.Action("service_call", "service_call")';
} else {
window.location.href = '#Url.Action("edit", "service_call", new { id = "CC" })'.replace("CC", callID);
}
}
I have try that objservice.callid variable store in viewbag and access on view it is not work.because view is not return controller.
can it is possible to store that variable in session variable then access on view.
Please give some suggestion ....
return as a json object with multiple values
[HttpPost]
public ActionResult create(ServiceCall objservice)
{
AllViewBags();
string result = PartnerMaster.CreateServiceCall(objservice);
if (result == "")
{
return Json(new { message = "Service Call = " + objservice.callID + " is Created successfully!", id = objservice.callID);
}
else
{
return Json(new {message = "This record is not added because of this error:=>" + result, id = 0});
}
}
and use this in the post success to redirect ...
Related
When the line getJSON is executed and there is routing to for example: https://localhost:44338/ArticleApi/GetNextArticles?id=12&quantity=2&filterName=Odziez
I get error:
Failed to load resource: the server responded with a status of 404 ()
Cannot find this page on localhost
GetNextArticles method in my ArticleApiController:
[HttpGet("{id}/{count}/{filterName}")]
public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
{
return _articleRepository.GetNextArticles(id, count, filterName);
}
in my view (.cshtml file):
$.getJSON('#Url.Action("GetNextArticles", "ArticleApi")' + "?id=" + last + "&quantity=" + quantity + "&filterName=" + filterCategory, function(data, status) {
for(var index in data) {etc...}}
GetNextArticles method:
public IEnumerable<Article> GetNextArticles(int id, int count, string filterName)
{
List<Article> articles = new List<Article>();
var categoryId = _context.Categories.Where(c => c.CategoryName == filterName).Select(c => c.CategoryId).FirstOrDefault();
for (int i = 0; i < count; i++)
{
var foundArticles = _context.Articles.Where(a => a.CategoryId == categoryId && a.ArticleId == id + i + 1).ToList();
if (foundArticles.Count() == 0)
{
return articles;
}
var article = foundArticles[0];
if (article != null)
{
article.Category = _context.Categories.Find(article.CategoryId);
articles.Add(article);
}
else
{
var nextArticles = _context.Articles.Where(a => a.CategoryId == categoryId && article.ArticleId <= id + i + 100).ToList();
if (nextArticles.Count != 0)
{
id = nextArticles.Min(a => a.ArticleId);
articles.Add(nextArticles.Where(a => a.ArticleId == id).First());
}
else
{
break;
}
}
}
return articles;
}
If you use [HttpGet("{id}/{count}/{filterName}")] in your Api, The Url passed into this api must be https://localhost:44338/ArticleApi/GetNextArticles/Id/count/filterName.
So, If you don't want to change the $.getJSON(..){...} in the View, You can change the api like:
[HttpGet]
public IEnumerable<Article> GetNextArticles([FromQuery]int id, int count, string filterName)
{
return _articleRepository.GetNextArticles(id, count, filterName);
}
You can see the Api works fine and it can be loaded in Swagger as well
According to the error, you could validate the names of the parameters that you are sending. Reviewing the code I realize that one of them is sent with the name "quantity" and in the controller you call it "count"
I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened
Here is the call function from my save button:
<script>
var op = '';
var op_dif = '';
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
alert(op + " " + op_dif); // I can see the value here
$.post("/Home/UpdateOP", {
'data': JSON.stringify([{
'op': op,
'opDiff': Op_dif
}])
}, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
</script>
My view where my update query is located:
public string UpdateOpsDiff(operation[] ops)
{
string res = "";
foreach(var op in ops)
{
string updatetQuery = "update sys.OP_difficulty set op_difficulty = #diff where op = #op;";
MySqlCommand updateCommand = new MySqlCommand(updatetQuery);
updateCommand.Connection = myConnection;
updateCommand.Parameters.AddWithValue("#diff", op.op_dif);
updateCommand.Parameters.AddWithValue("#op", op.op);
myConnection.Open();
int updatedRowNum = 0;
try
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
catch(MySqlException)
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
}
return res;
}
Controller where it reads the view query:
public string UpdateOp()
{
string data = Request.Form["data"];
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
return sys.UpdateOpsDiff(rows);
}
catch (JsonSerializationException je)
{
Console.WriteLine(je.Message);
return "{status:'DATA_FORMAT_ERROR'}";
}
}
Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.
Any suggestions or comments. TIA
Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:
[HttpPost]
public ActionResult UpdateOp(string data)
{
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
string result = sys.UpdateOpsDiff(rows);
// return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
return Content(result, "application/json");
}
catch (JsonSerializationException je)
{
// do something
return Json(new { status = "DATA_FORMAT_ERROR"});
}
}
Then set the AJAX callback to pass JSON string into action method mentioned above:
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
var values = { op: op, opDiff: op_dif };
$.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
Note:
The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:
res = string.Format(#"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);
I am trying to create some validation for a form.
The user can enter in account code, name, address, etc for companies. I need to create the validation for the name text box. If they enter a name that already exists then display the message "This name already exists on account code: " then display the account code.
The problem is I don't know how to get the account code of the company.
<asp:TextBox runat="server" ID="txtName" onblur="CheckIfNameExists(this.value)"></asp:TextBox>
function CheckIfNameExists(Name) {
PageMethods.CheckIfNameExists(Name,
OnCheckIfNameExists,
null
);
}
function OnCheckIfNameExists(result){
if(result){
alert("This Name already exists!");
}
else{
}
}
Web method for checking bool:
[WebMethod]
public static bool CheckIfNameExists(string Name)
{
try
{
if(Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name))
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
return true;
}
}
Right now the code just checks if the name already exists in the database. But I want to get the account code of the name in the database.
This is the code that searches the database:
public static bool CheckIfNameCreditorExists(int CompanyID, string Name)
{
DataSet ds = new DataSet();
string sql = "proc_CheckIfACCreditorExists";
string query = "SELECT c.* " +
" FROM Creditor c " +
" WHERE c.Company_ID = " + CompanyID + " AND c.Name LIKE '" + Name + "' ";
DataTable dt = new DataTable();
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
return true;
}
return false;
}
}
Change the return type of your method to string from bool
bool is replaced with string in below code snippet
public static string CheckIfNameCreditorExists(...
Now, change your return type. I am just rewriting your return lines only.
if (dt.Rows.Count > 0)
{
//Make sure to use right column name here
return string.format("{Exist: true, AccountNo: {0}}", dt.Rows["AccNo"]);
}
return return "{Exist: false, AccountNo: null}";
Finally, modify javascript method as below.
function OnCheckIfNameExists(result){
if(result.Exist){
alert("This Name already exists!");
alert("Associated Account Number is: " + result.AccountNo);
}
else{
}
}
Only possible issue is: Sometimes, returned json string will not be parsed automatically. In that case rather than directly referring result, you can parse Json to object and use its properties in javascript method.
I would call the method using jquery.
jquery ajax
function CheckIfNameExists(Name) {
$.ajax("CheckIfNameCreditorExists?companyID=[value]&name=[value]").done(
function(result) {
if(result){
alert("This Name already exists!");
}
else {
}
});
}
You can do it in POST or GET as you wish.
I'm pretty new to ASP.NET MVC, I been searching for a solution for this problem but I couldn't find any proper solution. I found some solutions here on stachoverflow but nothing has worked with me. Here are some links:
Possible to access MVC ViewBag object from Javascript file?
MVC 3 - Assign ViewBag Contents to Javascript string
Here is my ajax call to the server:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Prize/UploadPassport');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText)
if (data.nationality != "") {
$('#PassportData tbody').append('<tr><td data-title="#Web.Resources.MyResources.PassportNationality">' + data.nationality + '</td><td data-title="#Web.Resources.MyResources.PassportName">' + data.passportName + '</td><td><a><i id="viewApp_' + data.passportID + '" class="fa fa-search fa-lg" onclick="ViewPassport(' + data.passportID + ');"> <iframe id="img_' + data.passportID + '" class="costumeiframe"></iframe></i></a></td></tr>');
}
else {
//var errorMsg = data.errorMsg;
ShowDataValidationMessage("#ViewBag.FileError"); //here i'm getting an empty string
}
}
}
In my server side action I set ViewBag.FileError based on some conditions here it is:
public ActionResult UploadPassport(HttpPostedFileBase FileUpload, string PassportCopyNationality)
{
if (Condition)
{
//Database access
}
else
{
if (isFileAlreadyExist)
{
ViewBag.FileError = Web.Resources.MyResources.PassportAttachmentValidationForFile;
}
else if (file.ContentLength > 3145728 || !isFileTypeLegal)
{
ViewBag.FileError = Web.Resources.MyResources.FileError;
}
return Json(new { nationality = "", passportName = "", passportID = "" });
}
}
catch (IOException io)
{
return Json("File not uploaded");
}
}
The problem that I'm getting an empty string
Firstly, #ViewBag.FileError (inside your script) is razor code which is parsed on the server before your view is sent to the client, so unless you include ViewBag.FileError = someValue in the GET method that generates this view, then it will always equate to null.
Secondly, your UploadPassport() method is returning a JsonResult not a view, so ViewBag does not even exist. You can resolve this by adding the value to the JsonResult, for example
return Json(new { fileError = someValue, nationality = "", passportName = "", passportID = "" });
and then access it in the script
ShowDataValidationMessage("data.fileError");
on my view page , i am passing some values to controller by ajax request , on controller action, after checking , redirecting message value to view's controller.Adding message to model and pasisng model to view again with new model value.On second time( postback) model values passed to view as Json but new model value(which is message) cannot be catch by javascript.In my code it is Model.INFO
$.ajax({
type: "POST",
url: '#Url.Action("TeamSaveChanges", "Administrator")',
data: {
ID: '#Model.ID',
doctorID: doctorValue,
nurseID:nurseValue,
driverID:driverValue,
technicianID: technicianValue
},
dataType: "text",
success: function () { alert("#Model.INFO")},
error: function () { alert("Error occured!!!") }
});
Controller
public ActionResult TeamSaveChanges(Guid ID, Guid? doctorID, Guid? nurseID, Guid? driverID, Guid? technicianID)
{
try
{
using (var client = SoapProxyFactory.CreateDSrvGDSoapClient())
{
var emptyTeam = Guid.Empty;
var ambID = client.getAmbulanceIDbyTeamID(ID);
var baseresult = client.checkAmblanceTeamsforDuplicateMembers(ambID, ID);
if (doctorID == emptyTeam && nurseID == emptyTeam && driverID == emptyTeam && technicianID == emptyTeam )
{
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
else
{
foreach (var item in baseresult)
{
if(item.DOCTORCODE == doctorID && item.NURSECODE == nurseID && item.DRIVERCODE == driverID && item.TECHNICIANCODE == technicianID)
throw new Exception("The team with Same Members is exist." + "<p>(" + item.TEAMCODE + ")</p>");
}
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
catch (Exception exp)
{
string message = exp.Message;
return RedirectToAction("TeamMembers", "Administrator", new { ID = ID, message = message });
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult TeamMembers(Guid? ID,string message)
{
try
{
if (!ID.HasValue())
return RedirectToAction("Ambulance");
using (var client = SoapProxyFactory.CreateDSrvALLSoapClient())
{
Guid id = ID.Value;
var clientGD = SoapProxyFactory.CreateDSrvGDSoapClient();
var result = client.GetTeamMembers(id);
result.INFO = message;
if (message != null)
{
result.INFO = message;
return Json(result,JsonRequestBehavior.AllowGet);
}
return View(result);
}
}
This line:
success: function () { alert("#Model.INFO")},
Will only pull in the INFO of the model once because it renders the server value in the client. If you are expecting it to change, then you have to pass the result back to success, and accept the new value as such:
success: function (d) { alert(d); },
To return a value to it you have to return from the action:
return Content("SOMEVAL"); // or PartialView or something that is string data
However, redirecting to action isn't going to return a response to the caller, and may not be handled properly through AJAX, so I'm not 100% sure what the question is...
Why would you use AJAX for this? What is happening is your script is firing a request off to your controller, which sends the response back as data, not a redirect to a new webpage.
Just create a form that POSTs those variables to your controller in typical MVC fashion, you'll get the result you want.