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
});
});
Related
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 modal with input, i digit some emails and add to a list, later i want to pass this list of emails to my function that send emails.
var listEmails = [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
listEmails.push(text);
}
document.getElementById("sendEmail").onclick = function () {
#*location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails='+listEmails;
}
that is my function in Controller that receive a list of email to send
public void TestSendReport(List<string> ListMails)
Please try below code and try to call controller method using jQuery Ajax
var list= [];
document.getElementById("addEmail").onclick = function () {
var text = document.getElementById("recipient-email").value;
$("#Listmail").append('<li>' + text + '</li>');
list.push(text);
}
document.getElementById("sendEmail").onclick = function () {
var jsonText = JSON.stringify({ list: list});
$.ajax({
type: "POST",
url: "ProductMarketplace/TestSendReport",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() { alert("success"); },
failure: function() { alert("failed"); }
});
}
And use controller method like this,
[WebMethod]
public void TestSendReport(List<string> list)
{
}
document.getElementById("sendEmail").onclick = function () {
location.href = '#Url.Action("TestSendReport", "ProductMarketplace")?emails=' +
encodeURI(JSON.stringify(listEmails));
}
public void TestSendReport(List<string> emails)
{
}
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();
}
})
})
Wellcome!
I have a problem with passing data from JavaScript to MVC Controller. Im new to MVC so I probably miss something.
$("#example").keypress(function (event) {
var data = "example";
$.ajax({
url: "/example/example",
type: "POST",
dataType: "json",
data: { example: data },
success: function (example) {
var items = "";
$.each(data, function (i, example) {
items += "<option>" + example + "</option>";
});
$("#example").html(items);
}
});
});
public class PeoplePickerController : BaseController
{
// GET: PeoplePicker
public ActionResult PeoplePicker(object data)
{
if (HttpContext.Request.IsAjaxRequest())
{
IQueryable logins = (IQueryable)QueryDatabaseForUsersAndGroups((string)data, Context.Users);
return Json(new SelectList(example, "example"), JsonRequestBehavior.AllowGet);
}
return PartialView();
}
}
data parameter is always null.
I have a partial that I refresh via Ajax.
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
}
});
}
});
Refresh action:
[HttpPost]
public ActionResult Refresh(int id)
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
This works well, except that when an error (such as an HTTP exception) occurs, the error view is sent to the partial when I want it to be shown as the main view.
Error action:
public ActionResult Error(string message)
{
ViewBag.Message = message;
return View();
}
I have tried using Javascript (both in the view and returned by the controller) to redirect the browser, however both are buggy and I assume bad practice.
Try as
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
$('#partialHolder').html(result);
},
error: function(result){
//call new action
}
});
}
});
Assuming Error() returns a complete view (with layout and script/css), you could always try completely overwriting your document:
success: function (result) {
$('#partialHolder').html(result);
},
error: function(xhr) {
if(xhr.responseText) {
var newDoc = document.open("text/html", "replace");
newDoc.write(xhr.responseText);
newDoc.close();
}
}
This will effectively overwrite your entire dom and will cause you to lose everything that was on the page.
Credits for document rewrite to this answer
Try something like this
in your action
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return PartialView("~/Views/PartialView.cshtml", null);
}
}
so in your ajax success
if (result != null) {
//do your stuff
} else {
// the controller action returned a partial
$('#divInYourMain').html("Error 123");
}
I managed to solve this in a similar way to theLaw's answer, by using a try/catch block and the Content helper method to return a simple string which triggers a redirect.
Refresh Action:
[HttpPost]
public ActionResult Refresh(int id)
{
try
{
HomeViewModel model = new HomeViewModel();
model.id = id;
ViewBag.id = model.id;
PrepareModel(ref model);
return PartialView("~/Views/PartialView.cshtml", model);
}
catch
{
return Content("error");
}
}
View Javascript:
$("#SelectedId").change(function () {
var id = $("#SelectedId").val();
if (id > 0) {
$.ajax({
url: "/Home/Refresh",
data: { id: id },
type: "POST",
success: function (result) {
if (result == "error") {
location.replace("#Url.Action("General", "Error")");
}
else {
('#partialHolder').html(result);
}
}
});
}
});