I've been trying to make the "RedirecttoAction" statement work here but it doesn't budge. Here is the method:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CalloutAdmin/Index/");
}
And it is called by the following JQuery, which works perfectly:
$(function () {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate);
});
});
The only thing that does not happen is the page being refreshed, which was what the redirect should do. Can anyone advise?
UPDATE
What I am trying to do is update this Callout object, without redirecting to another view. I choose a technician from a dropdownlist and it automatically sets the callout's technician value to the one I chose from the dropdown.
You're returning the redirect to the AJAX request, and the AJAX request is loading the page in the background. If you want to have the entire page redirect you probably want to use the success callback in jQuery
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function() { document.location = "CalloutAdmin/Index/"; } );
If you want to have the action control the location of the redirect, you probably want to use the return a JsonResult or ContentResult from your action with the URL outputted from there have jQuery's success callback redirect the user.
Assuming that UpdateTech and Index both belong to CallOutAdminController then change your UpdateTech Method to look like:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index","CallOutAdmin");
}
Then make you jQuery function like this:
$(document).ready(function(e) {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
window.location = "/CallOutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate
});
});
Related
I am trying to send data and change view. I put breakpoint, second view worked but not show to me. I don't want to use Html.BeginForm because I am working with hmtl and javacript.
public ActionResult Second(int id)
{
List<Properties> users = GetData(id);
return View(users);
}
$('select').on('change', function (e) {
//var id = $(this).find(":selected").val()
var id = this.selectedIndex;
var targetUrl = '/Home/Second/' + id.toString();
$(this).load(targetUrl);
});
I Fix that
$('select').on('change', function (e) {
var id = this.selectedIndex;
var targetUrl = '/Home/Second/' + id.toString();
location.href = targetUrl;
});
I am implementing "show more posts" in my blogs list following
this example but I want to make a change and switch from using ViewData to ViewModel.
This the relevant code:
private void AddMoreUrlToViewData(int entryCount)
{
ViewData["ShowMore "] = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
}
that I switch to
ViewModel.ShowMore = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
the Index action of the example:
public ActionResult Index(int? entryCount)
{
if (!entryCount.HasValue)
entryCount = defaultEntryCount;
int totalItems;
if(Request.IsAjaxRequest())
{
int page = entryCount.Value / defaultEntryCount;
//Retrieve the page specified by the page variable with a page size o defaultEntryCount
IEnumerable<Entry> pagedEntries = GetLatestEntries(page, defaultEntryCount, out totalItems);
if(entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View("EntryTeaserList", pagedEntries);
}
//Retrieve the first page with a page size of entryCount
IEnumerable<Entry> entries = GetLatestEntries(1, entryCount.Value, out totalItems);
if (entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View(entries);
}
Here I add a lot of code to load the post from the db, the only code I think is relevant is that I swtich return View("EntryTeaserList", pagedEntries); to return View(myViewModel); after setting BlogsList and ShowMore property.
But my problem is in the javascript command:
$(function() {
addMoreLinkBehaviour();
});
function addMoreLinkBehaviour() {
$('#entryTeaserList #moreLink').live("click", function() {
$(this).html("<img src='/images/ajax-loader.gif' />");
$.get($(this).attr("href"), function(response) {
$('#entryTeaserList ol').append($("ol", response).html());
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
});
return false;
});
}
where
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
to take ViewData property and use it to replace the link.
How can I read the ViewModel Property instead?
I have an ASP.NET MVC application. I am trying to call a WebAPI controller. The controller works fine when I call it via $.get in jQuery. After finishing the callback function everything should stop and I should be able to see my web page. However after finishing the callback function the browser is taking me to the raw JSON view page in chrome. In IE it asks me if I want to download returned .json file. Why is this happening. Here is my code:
function onNLookupSearch() {
var uri = window.location.protocol + "//" + window.location.host;
var searchTerm = $("#nlookupsearch").val();
var resultUrl = window.location.href = uri + "/api/v1/GetNetworkName?networkName=" + searchTerm;
$.get(resultUrl, function (data1) {
localData1 = data1;
$("#sdnetworkselect").kendoDropDownList({
dataSource: localData1,
dataTextField: "NETWORK_NAME",
dataValueField: "NETWORK_ID"
});
$("#hdnetworkselect").kendoDropDownList({
dataSource: localData1,
dataTextField: "NETWORK_NAME",
dataValueField: "NETWORK_ID"
});
});
}
Here is my WebAPI controller code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using CPT2.Data;
namespace CPT2.Controllers
{
public class GetNetworkNameController : ApiController
{
private CMDBdbContext _ctx;
public GetNetworkNameController(CPT2.Data.CMDBdbContext ctx)
{
_ctx = ctx;
}
public IQueryable<CPT2.Data.network_sourceid_map> Get([FromUri] string networkName)
{
var result =
_ctx.network_sourceid_map.Where(
nw => nw.NETWORK_NAME.Contains(networkName) || nw.SOURCE_NAME.Contains(networkName));
var myList = result.Select(item => item.NETWORK_NAME + " - " + item.SOURCE_NAME + " [" + item.SOURCE_ID + "]").ToList();
//return myList;
return result;
}
}
}
Lets assume I search for "ESPN". That's the search term in the code above.
After this function is done I should stay on page however I am redirected to a raw view of the returned data by Chrome and IE asks me to save a JSON file.
I think your problem is this line:
var resultUrl = window.location.href = uri + "/api/v1/GetNetworkName?networkName=" + searchTerm;
You are setting the window.location.href which is redirecting the entire page to the API "page", which is why you're getting a .json file.
What I want is to add an object routed value when the user submits the form (ajax.beginform)
Depending on what the user chooses in the ConfirmDone function, i want to add an integer (SaveOption)
But i don't really know how to do it.
The confirmdone function is called but that's it, my controller action is'nt called. I probably need to return something?
Some Code: the start of the form
#using (Ajax.BeginForm("CreateFunctiebeschrijvingPartial", "Functiebeschrijving", new AjaxOptions { UpdateTargetId = "Functiebeschrijving", OnBegin = "return ConfirmDone()", OnSuccess = "handleSuccess" }, new {#id = frmID}))
{
The confirmdone function
function ConfirmDone() {
if (confirm("This form saves default as Concept, would you like to save it as completed? 1 = Completed, 2 = Concept")) {
//option 1: save as completed
$('#frmID').attr("SaveOption", 1);
}
else {
//Option 2: save as concept
}
}
The start of my controller action
//
// POST: /FunctieBeschrijving/CreateFunctiebeschrijvingPartial
[HttpPost]
public ActionResult CreateFunctiebeschrijvingPartial(NieuweFunctiebeschrijvingViewModel nfvm, int SaveOption)
{
When i don't use the confirm function, everything is posted as it should be!
function addDataToUrl(url, name, value){
var sep = url.indexOf('?') === -1 ? '?' : '&';
return url + sep + name + '=' + value;
}
function ConfirmDone() {
var form = document.getElementById('frmID');
if (confirm("This form saves default as Concept, would you like to save it as completed? 1 = Completed, 2 = Concept")) {
//option 1: save as completed
form.setAttribute('action',
addDataToUrl(form.getAttribute('action'), 'SaveOption', '1'));
}
else {
// Option 2: save as concept
}
}
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>