I have a slight problem with ajax. So first I'm gonna show you my actions.
Form:
<form id="QuestionForm">
#Html.TextBoxFor(model => model.Body, new { #class = "form-control", #placeholder = "Body" })
#Html.TextBoxFor(model => model.Text, new { #class = "form-control", #placeholder = "Text" })
</form>
Here's my script and ajax code:
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {data, #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Here's my controller action:
public JsonResult AddQuestion(SurveyQuestion model, int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
I didn't fill out every part of the code, some of it is hardcoded, because I'm going to do the actions later. But the problem is with sending two things.
If I don't send the Id and delete Id from the controller, it sends the serialized model well, but If I send them both, it gets the Id, but it doesn't get the model sent to him (text and body is null). How do I fix this?
You can do it like below:
$("#btnSubmit").click(function() {
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
// Add id like query string parameter like below
data: $('#QuestionForm').serialize() + '&id=' + #Model.Survey.Id,
success: function() {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Pass id as query string parameter
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=" + '#Model.Survey.Id',
data: {data, #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
In controller use FromUri attribute before the parameter
public JsonResult AddQuestion(SurveyQuestion model,[FromUri]int id)
{
SurveyQuestion question = new SurveyQuestion();
question.Body = model.Body;
question.CreatedOn = DateTime.Now;
question.ModifiedOn = DateTime.Now;
question.Priority = 0;
question.SurveyId = id;
question.Text = model.Text;
question.Type = QuestionType.Text;
_db.SurveyQuestions.Add(question);
_db.SaveChanges();
return Json(question, JsonRequestBehavior.AllowGet);
}
Try this, passing multiple parameters in post or you can pass using querystring as shown in other answers
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion",
data: {model : data, id: #Model.Survey.Id},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Controller
public ActionResult ActionName(SurveyQuestion model, int id)
{
Your Code .......
}
you can put id in the url
$("#btnSubmit").click(function () {
var data = $('#QuestionForm').serialize();
$.ajax({
type: "POST",
url: "/Survey/AddQuestion?id=#Model.Survey.Id",
data: {data},
success: function () {
$("#AddQuestion").modal("hide");
//alert("Survey Added");
location.reload();
}
})
})
Related
i have problem to update selected option .The database can be update ,but it update for all data .i just want to update current row only
javascript :
$(document).ready(function () {
$('#table_refund').on('change' ,'select', function() {
var data= $(this).closest('tr');
var status = $('option:selected',this).val();
alert(status);
$.ajax({
type: "get",
url: "/financial/approve/refund",
data: {status: status },
dataType: "JSON",
success: function (response) {
$('.alert').show();
}
});
});
controller:
public function studentrefund(Request $req)
{
//update table
data = Refund::find($req->userid);
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
You Need to check particular Id and that userID so you get current row.
Controller::
public function studentrefund(Request $req)
{
//update table
$data = Refund::where('id',$req->id)->where('userid',$req->userid)->first();
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
You can Use fundOrFail the findOrFail and firstOrFail methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown laravel.com/docs/5.1/eloquent#retrieving-single-models
public function studentrefund(Request $req)
{
//validate user id
request()->validate([
'userid' => 'required',
]);
//update table
$data = Refund::findOrFail($req->userid);
$data->status = $req->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
option :
<select id="table_refund">
<option data-id="{{ $row->id }}" value="Aktive">Test Data</option>
</select>
Jquery :
$(document).ready(function() {
$('#table_refund').on('change', 'select', function() {
var id = $(this).data('id');
var status = $('option:selected', this).val();
$.ajax({
type: "POST",
url: "{{ url('financial/approve/refund') }}",
data: {
"id": id,
"status": status,
},
dataType: "JSON",
success: function(response) {
$('.alert').show();
}
});
});
Controller :
public function studentrefund(Request $request)
{
$data = Refund::findOrFail($request->id);
$data->status = $request->status;
$data->save();
return response()->json(['success'=>'Saved successfully.']);
}
Description of the situation:
I have selectbox, I choose a person there (there, I download the entire list of employees from the database). I have two more fields (I would like to enter values from other columns (same row) (data of this employee))
Controller
using AppEcp.Models;
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
namespace AppEcp.Controllers
{
public class UzytkownicyController : Controller
{
private readonly UzytkownicyDbContext _uzytkownicyContext;
public UzytkownicyController(UzytkownicyDbContext uzytkownicyContext)
{
_uzytkownicyContext = uzytkownicyContext;
}
public IActionResult GetItems(DataSourceLoadOptions loadOptions)
{
var GetMethod = _uzytkownicyContext.Uzytkownicy.Where(i => i.Firma == "Pekao Leasing").Select(i => new
{
i.Id,
i.Nazwa,
i.Departament,
i.Login
});
return Json(DataSourceLoader.Load(GetMethod, loadOptions));
}
[HttpGet]
public ActionResult GetDepartmentAndManager(string nazwaValue)
{
var danePracownika = _uzytkownicyContext.Uzytkownicy.Where(x => x.Nazwa == nazwaValue).Select(s => new
{
UserDepartament = s.Departament,
UserManager = s.Manager
});
return Json(danePracownika);
}
}
}
I tried:
cshtml page
#(Html
.DevExtreme()
.SelectBox()
.ID("Id_name")
.DataSource(d => d
.Mvc()
.Controller("Uzytkownicy")
.Key("Id")
.LoadAction("GetItems")
)
.DisplayExpr("Nazwa")
.ValueExpr("Id")
.SearchEnabled(true)
.OnValueChanged("getDepAndMan")
)
#(Html.DevExtreme().TextBox()
.ID("Id_department"))
#(Html.DevExtreme().TextBox()
.ID("Id_manager"))
<script type="text/javascript">
function getDepAndMan() {
var nazwaValue = document.getElementById("Id_name").value;
$.ajax({
type: "GET",
url: '#Url.Action("GetDepartmentAndManager", "Uzytkownicy")',
contentType: 'application/json; charset=utf-8',
data: { nazwaValue : nazwaValue},
dataType: "json",
success: function (data) {
document.getElementById("Id_department").value = (data.UserDepartament);
document.getElementById("Id_manager").value = (data.UserManager);
},
error: function () {
alert("bad code noob");
}
});
}
</script>```
Do not work:
The code does not throw an error, but does not enter the downloaded data into text boxes
Access the required widget using its "options" api (refer to this demo), for example:
success: function (data) {
alert(data.UserDepartament + " " + data.UserManager);
//document.getElementById("Id_department").value = (data.UserDepartament);
//document.getElementById("Id_manager").value = (data.UserManager);
$("#Id_department").dxTextBox("instance").option("value", data.UserDepartament);
$("#Id_manager").dxTextBox("instance").option("value", data.UserManager);
}
I'm new to Ajax but I want to delete a row from the grid with ajax.
The code below doesn't work. Could you give me some insights?
Whenever the checkbox is checked then it must delete the row.
#Html.Grid(Model.RequestList.OrderByDescending(x => x.CreateDate)).Columns(c => {
c.Add().Titled("View").Encoded(false).Sanitized(false).SetWidth(30).RenderValueAs(p => Html.CheckBox("checkedz",(int)p.Status==1?true:false,new {#class="aaa",onclick="aaa('"+p.Id+"')" }));
})
.WithPaging(20).Selectable(false)
function aaa(id) {
var idyus = id;
var chbox = $(this);
$.ajax({
type: "POST",
url: '#Url.Action("Remove", "Request", new { Area = "Options" })',
success: function () {
chbox.parent().parent().remove();
console.log("success");
}
});
}
public ActionResult Remove(Guid? Id)
{
if (!Id.HasValue)
{
return NotFound();
}
_requestService.Remove(Id.Value);
_requestService.Save();
return RedirectToAction("Index");
}
I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).
I am using MVC. In my one page, if i type one value that is process, if it exists the related details will populate in other all fields. how to do this in Ajax call?
Controller:
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return View("Call",partner);
}
Call is the Aspx page.
In view:
<script type ="text/javascript">
$('#getPincode').text('Get Pincode') // Sets text for company.
.attr('href', '#');
$("#getPincode").click(function () {
$('#getPincode').text('Get Company')
.attr('href', 'GetDetail?pincode=' + $('#Pincode').val());
});
$("#Pincode").blur(function () {
$("#checkPincode").trigger('click');
});
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
But i don't know how to populate the result into my view which means editor fields???
View:
<%:Html.TextBox("Address")%>
You can try this one:
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner, JsonRequestBehavior.AllowGet);
}
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = {'pincode': name};
$.ajax({
type: "POST",
url: "/GetDetail",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
return it as a jsonResult
public JsonResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return Json(partner);
}
or if you want to load partial view load it as
public ActionResult GetDetail(string pincode)
{
Partner partner= null;
if (!string.IsNullOrEmpty(pincode))
{
partner= _channelRepository.GetpartnerByPincode(pincode);
}
return PartialView("Call",partner);
}
<div id="myDiv"></div>
$(document).ready(function () {
$('#checkPincode').click(function () {
var name = $('#Pincode').val();
var data = 'pincode=' + name;
$.ajax({
type: "GET",
url: "GetDetail",
data: data,
success: function (data) {
$('#myDiv').html(data);
}
});
return false
});
});