I am beginner to jquery-ajax. I trying to get Employee data into front-end using ajax method. But the url is not calling the action method. Please check the below code
MyScripts.js:
function fn_test()
{
var eno = $("#t1").val();
$.ajax({
cache :false,
url: "Home/GetEmpData/"+eno,
type: 'GET',
data:"",
contentType:'application/json;',
success: function (response)
{
var str = "Ename :" + response.EmpName + "<br >";
str += "Job :" + response.Job + "<br >";
tr += "Salary :" + response.Salary + "<br >";
str += "Deptno :"+response.DeptNo+"<br >";
$("#sp1").html(str);
}
});
}
Action method in HomeController.cs
public ActionResult GetEmpData(int id)
{
Employee obj = db.Employees.Find(id);
return Json(obj, JsonRequestBehavior.AllowGet);
}
Index.cshtml
Enter your name :
<input type="text" id="t1" /><br /><br />
<input type="button" id="b1" onclick="fn_test()" value="get message" /><br /><br />
<span id="sp1"></span>
Please help me.
Construct you urls correctly using
url: '#Url.Action("GetEmpData", "Home")',
and pas the data using
data: { id: eno },
and remove
contentType:'application/json;',
Edit
Since your script is in a separate file, modify your html to
<input type="button" id="b1" data-url="#Url.Action("GetEmpData", "Home")" value="get message" />
Then change the script to
$('#b1').click(function() {
$.ajax({
cache :false,
url: $(this).data('url'),
type: 'GET',
data: { id: $("#t1").val() },
success: function (response) {
...
}
});
});
you are passing parameter as query string .you have tell the browser this using ? sign before variable name that you had used in controller and after this you can assign value to this.
function fn_test()
{
var eno = $("#t1").val();
$.ajax({
cache :false,
url: "Home/GetEmpData?parameterNameInController="+eno,
type: 'GET',
data:"",
contentType:'application/json;',
success: function (response)
{
var str = "Ename :" + response.EmpName + "<br >";
str += "Job :" + response.Job + "<br >";
tr += "Salary :" + response.Salary + "<br >";
str += "Deptno :"+response.DeptNo+"<br >";
$("#sp1").html(str);
}
});
}
public ActionResult GetEmpData(int id)
{
Employee obj ;
try{
obj = db.Employees.Find(id);
return Json(obj, JsonRequestBehavior.AllowGet);
}catch(Exception ex)
{ obj=new Employee();
//return empty object
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
Related
I'm having problems with an form.
I need to submit a form with ajax with fileinput in the form. In this form, I use the plugin with fileinput. This is the website
Here is my code:
<link href="~/Content/Plugin/bootstrap-fileinput-master/css/fileinput.min.css" rel="stylesheet" />
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput.min.js"></script>
<script src="~/Content/Plugin/bootstrap-fileinput-master/js/fileinput_locale_zh.js"></script>
#using (Ajax.BeginForm(null, null, new AjaxOptions(){
HttpMethod = "post",Url = Url.Action("Upload", "WorkItem"),
InsertionMode = InsertionMode.Replace, LoadingElementDuration = 2000,
OnSuccess = "completed" },
new { role = "form", enctype = "multipart/form-data" }))
{
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">TITLE</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">POINT</span>
<input type="text" name="Point" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">DESCR</span>
<input type="text" name="Descr" class="form-control" aria-describedby="basic-addon1">
</div>
<div class="m-b-5"></div>
<input id="file-0a" name="file" class="file" type="file" data-min-file-count="1">
<br />
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
}
When I click the submit button, no file can be accepted. What is going wrong?
As #Stepher Muecke told #Ajax.BeginForm can not be used to post Files.
I dont have a idea about plugin.I use the following method:
$("#btnUploadExcel").click(function () {
if ($("#newuploadexcel").val() == '') {
notie.alert(2, "Please Select Any File", 2);
}
else {
if (window.FormData!= undefined) {
var fileUpload = $("#newuploadexcel").get(0);
var files = fileUpload.files;
// Create FormData object
var fileData = new FormData();
// Looping over all files and add it to FormData object
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
// Adding one more key to FormData object
// fileData.append('contentId', contentId); commented as now supplierId is passed in the excel itself
$.ajax({
url: '/BulkStock/UploadExcel',
data: fileData,
type: "POST",
async: true,
dataType: 'json',
contentType: false,
processData: false,
success: function (result) {
var data = result.message;
//1=Failure, No excel
//2= Failue, with excel
//3=success, no excel
if (result.errmsg == '3') {
notie.alert(1, data, 6);
}
else if (result.errmsg == '1') {
notie.alert(3, data, 6);
}
else {
window.location = result.link;
notie.alert(3, data, 10);
}
},
error: function (response) {
console.log(response.responseText);
},
failure: function (response) {
console.log(response.responseText);
}
});
$("#newUpload").modal('hide');
} else {
notie.alert(3, "FormData is not supported.", 3);
}
}
});
And my controller to get file is:
public JsonResult UploadExcel()
{
string filePath = String.Empty;
string fileName = string.Empty;
if (Request.Files.Count > 0)
{
// Get all files from Request object
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
fileName = file.FileName;
string extension = System.IO.Path.GetExtension(fileName);
if (extension.Equals(".xls") || extension.Equals(".xlsx"))
{
var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3DigitRandomNumber = now.Substring(now.Length - 7, 3);
fileName = (file.FileName.Replace(extension, "")) + (my3DigitRandomNumber + extension);
filePath = string.Format("{0}/{1}", Server.MapPath("~/excelfiles"), fileName);
file.SaveAs(filePath);
}
}
}
}
Create a folder with the name "excelfiles" in your solution
I am trying to get the viewmodel on the page to update when a partial view is updated via an ajax post. The partial view updates correctly but on the next update call the model seesm to have reverted back to the orginal state.
The partial view is a table and I am either adding or deleting a row. The codde is included below any ideas as to how this can be done.
page code is
<div class="filters">
<fieldset class="source">
<legend>Search Attributes</legend>
<div id="attributes-filter">
#Html.Partial("_EditSearchQuery")
</div>
</fieldset>
</div>
<div>
<a id="addRowLink" class="add-row-link" href="#">Add new clause</a>
</div>
</div>
</div>
-- partial view is
<table id="searchClauses" class="clauses">
<tbody>
<tr class="header">
<td class="add-remove"></td>
<td class="logical">And/Or</td>
<td class="field">Field</td>
<td class="operator">Operator</td>
<td class="value">Value</td>
</tr>
#foreach (SearchClause item in Model.searchClauses)
{
<tr class="clause clause-row" id=#item.RowID>
<td class="add-remove">
<a href="#" title="Remove this filter line" id=#item.ID >Delete</a>
</td>
<td>
#Html.DropDownListFor(modelitem => item.logicalTypeValue, new SelectList(item.logicalTypeList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.DropDownListFor(modelitem => item.fieldListValue, new SelectList(item.fieldList, "Value", "Text", "Selected"))
</td>
<td>
#Html.DropDownListFor(modelitem => item.operatorListValue, new SelectList(item.operatorList, "Value", "Text", "Selected"), new { style = "width: 60px" })
</td>
<td>
#Html.TextBoxFor(modelitem => item.valuesList[0], new { style = "width: 130px" })
</td>
</tr>
}
</tbody>
-- script
<script type="text/javascript">
$(function () {
// Save quiz view - new or existing.
$("#attributes-filter").on("click", "a", function () { // A jQuery delegated event - #EditQuiz is always present, a.SaveQuiz only exists when the _ElearningQuiz partial view is loaded.
deleteRow($(this).attr("id"));
});
function deleteRow (id) {
var rowData = {
'id': id,
'model' : #Html.Raw(Json.Encode(Model))
};
$.ajax({
url: "/Participant/DeleteClause",
type: "POST",
data: JSON.stringify(rowData),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
};
$("#addRowLink").click(function () {
var model = #Html.Raw(Json.Encode(Model))
$.ajax({
url: "/Participant/AddClause",
type: "POST",
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function (result) {
$("#attributes-filter").html(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Status: " + textStatus + " Error: " + errorThrown);
}
});
});
});
</script>
-- controllers
[HttpPost]
public ActionResult AddClause(DynamicSearchModel model)
{
int campaignId = SessionManager.CampaignId;
int clientId = SessionManager.ClientId;
var newClause = _participantServiceClient.NewSearchClause(campaignId, clientId, 2);
newClause.ID = model.searchClauses.Count + 1;
model.searchClauses.Add(newClause);
return PartialView("_EditSearchQuery", model);
}
[HttpPost]
public ActionResult DeleteClause(string id, DynamicSearchModel model)
{
int _id = int.Parse(id);
model.searchClauses.RemoveAt(_id - 1);
return PartialView("_EditSearchQuery", model);
}
I am working with Asp.Net MVC4, I need to retrieve the date and time from the server and not the client. To restore them when I must click a button in the view, for example the name of the button "Nuevo" and from the view so I defined, the event is called by javascript in Action define the controller (Home) and ActionResult (Nuevo):
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ }),
success: function () {}
});
}
</script>
On receipt the data controller in the New ActionResult as follows:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return View(persona);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
What I need to do is to insert a new record (by clicking on the button "Nuevo") I load the default server time and date in different textbox.
Running this example enters the New ActionResult but to return to the data to view the TextBox is void, I tried other fields and the same result.
Any suggestions or help with this problem.
regards
Ricardo
There are basically two different routes you usually take when creating an AJAX action: letting the server render the HTML, or just sending data back to the browser and let the browser render the HTML. The code you have posted is a mixture of the two - that's why it's not working. The jQuery AJAX call is expecting JSON data back from the server, but the server is sending the HTML rendered by the Views\Home\Nuevo.cshtml view. Let's look at what these two different approaches might look like.
Server-Rendered Approach
You need to add an HTML element that will display the result. We will call it NuevoResult. And we also need some code that will put the response there. The easiest way is jQuery's .html() method.
<div id="NuevoResult"></div>
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'html',
success: function (data) {
$('#NuevoResult').html(data);
}
});
}
</script>
We also need a Views\Home\Nuevo.cshtml view for the server to render. It might look like:
#model MyCoolNamespace.Persona
<h3>New person created!</h3>
<p>Created on #string.Format("{0:d}", Model.Fecha) at #string.Format("{0:t}", Model.Hora).</p>
This is all the HTML we want to return from this action. We don't want it to be wrapped in any layout. To do this, we need to make sure we return PartialView(persona) instead of return View(persona).
Browser-Rendered Approach
For the browser rendered approach, we'll go ahead and have the HTML ready on the browser, but hidden. We'll fill it in with the correct information and display it when we receive a response from the server.
<div id="NuevoResult" style="display:none">
<h3>New person created!</h3>
<p>Created on <span id="Fecha"></span> at <span id="Hora"></span>.</p>
</div>
<script type= "text/javascript">
function ParseJSONDateTime(value) {
// from http://stackoverflow.com/questions/206384/how-to-format-a-json-date/2316066#2316066
return new Date(parseInt(value.substr(6)));
}
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
// ... also 'contentType' and 'data' if you're actually sending anything to the server...
dataType: 'json',
success: function (data) {
$('#Fecha').text(ParseJSONDateTime(data.Fecha).toLocaleDateString());
$('#Hora').text(ParseJSONDateTime(data.Hora).toLocaleTimeString());
$('#NuevoResult').show();
}
});
}
</script>
And then in the MVC action, use return Json(persona) to send the data back to the browser.
A few more notes...
The .NET DateTime structure holds both date and time information, so there's no need to have separate Fecha and Hora properties. Consider replacing with a single CreatedTimestamp property.
If you're still having trouble, Firefox's Firebug extension, Internet Explorer's Developer Tools, and Chrome's Developer Tools can be very helpful in figuring out what is wrong, allowing you to see exactly what was returned from the server.
Hi if i'm correct the problem is that the textbox values remain empty after you fired the function. The reason behind this is that your javascript function returns the data in the
success : function() {} part.
So what you have to do is return some kind of Json and then place the correct values in the textbox.
Javascript:
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
success: function(data) {
//Do stuff with your data
}
});
c#:
[HttpPost]
public ActionResult Nuevo()
{
Persona persona = new Persona();
persona.Fecha = DateTime.Now;
persona.Hora = DateTime.Now;
return Json(persona, JsonRequestBehavior.AllowGet);
}
This is my view, I use typed views:
#model MvcJavaScript.Models.Persona
<script type= "text/javascript">
function Nuevo() {
$.ajax({
url: '#Url.Action("Nuevo", "Home")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({}),
success: function (data) {
}
});
}
</script>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { sololectura = true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { sololectura = true })</td>
</tr>
</tbody>
</table>
}
If you are returning just a json object from the post call, you can write the success function in you ajax post back like below.
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
However if you are returning the view itself (which it looks like from your code), write the success function like this
success : function(data) {
$('#formContainer').html(data); // where formContainer is the control containing your form - may be an html body.
}
EDIT
since you have posted the view, change the Html.TextBoxFor lines for Fecha and Hora like below and use the success function given further below,
#Html.TextBoxFor(u => u.Fecha, new { sololectura = true, id="inputFecha" })
#Html.TextBoxFor(u => u.Hora, new { sololectura = true, id="inputHora" })
success : function(data) {
$('#inputFecha').html(data.Fecha);
$('#inputHora').html(data.Hora);
}
You can try this:
C#
[HttpPost] // Why do you need to use POST method?
public JsonResult Nuevo()
{
return Json(new { Fecha = DateTime.Now, Hora = DateTime.Now });
// if use get: return Json(object, JsonRequestBehavior.AllowGet);
}
HTML:
<button id="button-nuevo">Nuevo</button>
<h2>Registro persona</h2>
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "formPersona" })){
<input type="hidden" id="url-nuevo" value="#Url.Action("Nuevo", "Home")" />
<table cellpadding="4" class="td.headerTabsColor">
<tbody>
<tr>
<td><label>Fecha : </label>#Html.TextBoxFor(u => u.Fecha, new { #readonly=true })</td>
</tr>
<tr>
<td><label>Sexo : </label>#Html.TextBoxFor(u => u.Sexo, new { style = "width:225px", sololectura = false })</td>
</tr>
<tr>
<td><label>Hora : </label>#Html.TextBoxFor(u => u.Hora, new { #readonly = true })</td>
</tr>
</tbody>
</table>
}
JS
function dateFormat(d) {
var date = d.getDate(),
month = d.getMonth() + 1,
year = d.getFullYear();
retur (month > 9 : month ? '0' + month) + "/" + (date > 9 : date ? '0' + date) + "/" + year;
}
$('#button-nuevo').bind('click', function(event) {
var $formContext = $('#formPersona');
$.post($('#url-nuevo').val(), {}, function(data){
//UPDATE
var fecha = new Date(parseInt(data.Fecha.substr(6, 13)));
var hora = new Date(parseInt(data.Hora.substr(6, 13)));
$formContext.find('#Fecha').val(dateFormat(fecha));
$formContext.find('#Hora').val(dateFormat(hora));
}, "json");
});
Update based on this answer
Helo all,
I am able to post to controller using ajax.post, but on success how can I make my view refresh with new data.
Do I need to usn #Html.BeginForm to do this?
This is my view.
<div>
<p>Order lines allocates to <b>#Model.Name (#Model.Code) </b>
</div>
#if (Model.OrderLineAllocations.Any())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column(header: "Dispatched", style: "row-selector", format: #<text><input name="chkSelected" class="myCheckbox" onclick="expandableEvent(this)" type="checkbox" value="#item.IdAllocation" /></text>),
grid.Column(header: "Order Ref", format: item => item.OrderLineItem.OrderLine.Order.OrderRef)
),
tableStyle: "expandable-table",
rowStyle: "expandable-master-row",
htmlAttributes: new { id = "gridLineAllocations" })
<br />
<input type="hidden" id="hidUnselectedValues" name="hidUnselectedValues" />
<input type="submit" name="action" value="Dispacth" id="btnDispacth" />
<input type="submit" name="action" value="Revert" id="btnRevert" />
}
else
{
#Html.Raw("No records found....");
}
And this is my ajax post
$(document).ready(function() {
unSelected = [];
$("#btnDispacth").click(dipatchAllocations);
$("#btnRevert").click(revertAllocations);
});
function dipatchAllocations() {
var objInputEmail = $("#hidUnselectedValues");
if (objInputEmail != null) {
var id = objInputEmail.val();
if ((id != null) && (id != "")) {
$.ajax({
type: 'POST',
url: '/Batch/GetData',
data: '{ "allocationId" : "' + id + '","batchId" : "' + #Model.Id + '" }',
contentType: "application/json; charset=utf-8",
//contentType:"application/x-www-form-urlencoded",
traditional: true,
success: subscribed,
error: errorInSubscribing
});
} else {
alert('Please enter a valid email address in order to subscribe.');
}
}
};
This is my controller action
[HttpPost]
public ActionResult GetData(long[] allocationId,long batchId)
{
var model = context.GetData(batchId)
model.Name = "asdaksdjaksdj";
return View("Finalize", model);
}
I am having some idea, I have to do that on success call back. But I am not sure how to bind my updated model to the view at client side.
Thanks
There is no simple "rebind" method inside mvc, it's still html, css and js at the end.
I see 2 options to achieve desired behaviour.
option 1. Override rendered content with the result of POST
In this case your View will look similar to:
<div id="content">
<div>
<p>Order lines allocates to <b>#Model.Name (#Model.Code) </b>
</div>
...
else
{
#Html.Raw("No records found....");
}
</div>
On javascript:
$.ajax({
type: 'POST',
url: '/Batch/GetData',
dataType: "html",
success: function(data, textStatus, jqXHR){
$('#content').html(data);
}
});
option 2. Fill rendered html from javascript on every load
This will require to move Razor logic to javascript.
Your view will look like:
<div>
<p>Order lines allocates to <b id="NameAndCode"></b>
</div>
And javascript will fill the gaps:
$(function(){
var model = {
NameAndCode: "#Model.Name (#Model.Code)"
}
fillView(model);
})
var fillView = function(data){
$('#NameAndCode').html(data.NameAndCode)
}
$.ajax({
type: 'POST',
url: '/Batch/GetData',
dataType: "json",
success: function(data, textStatus, jqXHR){
fillView(data);
}
});
It's just a small piece just to show the idea.
It depends on case which option to choose.
script
<script type="text/javascript">
$(document).ready(function () {
$('musteri_sno').change(function () {
$('form_sayac_secimi').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
}
});
}
return false;
});
});
});
</script>
html
#using (Html.BeginForm("SayacSecimiPartial", "SayacOkumalari", FormMethod.Post, new { id = "form_sayac_secimi" }))
{
<table>
<tr>
<td>
#Html.DropDownList("musteri_sno", (SelectList)ViewBag.musteri_id, "--Müşteri Seçiniz--", new { id = "musteri_sno" })
</td>
<td>
#Html.DropDownList("sayac_no", Enumerable.Empty<SelectListItem>(), "-- Sayaç Seçiniz --", new { id = "sayac_no" })
</td>
<td>
<input type="submit" value="Uygula" />
#Html.Hidden("sno", new { sno = ViewData["sno"] })
</td>
</tr>
</table>
}
I want to fill second dropdown with values that is returned from first one.How can I do this?
Thanks.
In the success callback of your ajax call, build the option tag filled with the values you are returned and then append it to the select tag named "sayac_no".
success: function(result) {
var opt = '';
for (var i = 0; i < result; i++) {
opt += '<option value="' + result[i].value + '">' + result[i].name + '</option>';
}
$('select[name=sayac_no]').html(opt);
}
I suppose the result object is a list of objects with two properties, name and value.
Modify it accordingly to your needs and improve it because this is just a very basic version.