response.redirect in umbraco mvc surface controller - umbraco7

Hi can anyone help with this.
I have an action result in an umbraco surface controller. if the model is valid i then want to redirect to another page, but for some reason nothing I try will redirect. the things I have tried so far are
return RedirectToAction("actionname", "controller", "routevalues")
return RedirectToAction("TeamUpdatePage", "TeamUpdatePageSurface", new { i = id });
return JavaScript("$(function() { window.location.href = '/contacts/teams/update?i=" + id + "'; });");
return this.Redirect("/contacts/teams/update?i=" + id);
return new RedirectResult("/contacts/teams/update?i=" + id, false);
return RedirectToUmbracoUrlResult("/contacts/teams/update?i=" + id);
return RedirectToCurrentUmbracoPage("/contacts/teams/update?i=" + id);
return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { action = "TeamUpdatePage", controller = "TeamUpdatePageSurface" }));
Response.Redirect("/contacts/teams/update?i=" + id);
return Redirect("/contacts/teams/update?i=" + id);
return new RedirectResult("/contacts/teams/update?i=" + id);
Can anyone tell me why nothing seems to work, and what I can use that will work?
thanks

Related

Post ajax values to MVC Action Result

Ok, so I have the following Ajax get request going to a [HttpPost] controller method in an ASP.NET MVC 5 application.
The javascript function shown here successfully posts the values to the server side:
<script>
function get_row() {
var one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
var two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
var result = one + "," + two;
//var result = {};
//result.one = document.getElementById("data_table").rows[1].cells[0].innerHTML;
//result.two = document.getElementById("data_table").rows[1].cells[1].innerHTML;
if (result != null) {
$.ajax({
type: 'get',
url: "/Manage/CreateGroupRoleRestriction",
//url: '#Url.RouteUrl(new{ action= "CreateGroupRoleRestriction", controller= "Manage", one = "one", two = "two"})',,
data: { one, two },
//params: { one, two }
/*dataType: String,*/
//success: alert(result)
});
}
else {
alert("Error");
}
}
</script>
However, the issue is that the string values will not post to the Action Result, see below.
The values "one" and "two" are null.
[Authorize(Roles = "Admin")]
[HttpPost]
[Route("/Manage/CreateGroupRoleRestriction?{one,two}")]
[ValidateAntiForgeryToken]
public ActionResult CreateGroupRoleRestriction(FormCollection formCollection, string message2, string one, string two)
{
UserDataBusinessLayer userDataBusinessLayer = new UserDataBusinessLayer();
userDataBusinessLayer.Restrict1(message2);
UserDataBusinessLayer userDataBusinessLayer2 = new UserDataBusinessLayer();
userDataBusinessLayer2.Restrict2();
try
{
UserData userData = new UserData();
TryUpdateModel(userData);
if (ModelState.IsValid)
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer3 = new UserDataBusinessLayer();
userDataBusinessLayer3.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
else
{
userData.RoleName = formCollection["RoleName"];
UserDataBusinessLayer userDataBusinessLayer4 = new UserDataBusinessLayer();
userDataBusinessLayer4.CreateGroupRestriction(userData, message2, one.ToString(), two.ToString());
return RedirectToAction("CreateGroupRoleRestriction");
}
}
catch (Exception ex)
{
Logger.Log(ex);
return RedirectToAction("CreateGroupRoleRestriction");
}
}
Please try changing 'type' in ajax to 'post'.
type: 'post'

Ajax Call fails because of number of arguments

Ajax Call to msgcall method:
PopAjaxPost('mesaj/popup/msgcall/' + i + '/' + $('input#mesajkategori').val(), mysarr, function (data) {
if (data.Durum == '1') {
$wrapper.html('Mesaj<div class="preview"><div class="block"><strong>Gönderen:</strong>'
+ data.Data.Mesaj.Gonderen + '<br /><p>Sayın <strong>' + data.Data.Mesaj.Alici + '</strong></p><p>'
+ data.Data.Mesaj.Mesaj + '</p></div>' + (data.Data.Mesaj.SecenekId > 1 && !giden ? ('<input type="submit" value="Cevapla" onclick="mesajcevapla('
+ data.Data.Mesaj.MesajId + ');return false;" style="margin-bottom: 8px;">') : '') + '</div>');
}
else {
}
});
Here is msgcall method with three arguments:
[HttpPost]
[AjaxException]
[UserFilter]
public ActionResult MsgCall(string id, string pid, MsgHire model)
{
....
}
It does not invoke the msgcall method with the supplied arguments. If I remove the + i + '/', it invokes the msgcall method. What am I doing wrong?
From Route.config:
routes.MapRoute("MesajPopup", "mesaj/popup/{action}/{id}",
new { controller = "Mesaj", action = "Liste", id = UrlParameter.Optional });
routes.MapRoute("Mesaj", "mesaj/{action}/{id}",
new { controller = "Mesaj", action = "Liste", id = UrlParameter.Optional });
There is no configuration for additional parameter named pid, so you should define a maproute for this parameter.
Add something like this line:
routes.MapRoute("Msg_Call", "mesaj/popup/{action}/{id}/{pid}",
new {
controller = "Mesaj",
action = "Liste",
id = UrlParameter.Optional,
pid = UrlParameter.Optional
});

Asp.NET MVC ajax is loading bad page

I have a layout page inside which i have a table with delete button
when i press a delete button it is showing some thing like .
my ajex option is like.
#{
AjaxOptions xPost = new AjaxOptions();
xPost.HttpMethod = "POST";
xPost.Confirm = "Do you wish to submit this form ?";
xPost.OnBegin = "OnBegin";
xPost.OnComplete = "OnComplete";
xPost.OnFailure = "OnFailure";
xPost.OnSuccess = "OnSuccess";
xPost.LoadingElementDuration = 1000;
xPost.LoadingElementId = "divProgress";
xPost.UpdateTargetId = "divResponse";
xPost.InsertionMode = InsertionMode.Replace;
}
and on delete i am subbmiting the form to a controll like
public ActionResult Delete(int id)
{
ContactPersonManager.Delete(id);
return RedirectToAction("List");
}
As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Delete(int id)
{
ContactPersonManager.Delete(id);
return Json(new { success = true, redirecturl = Url.Action("List") });
}
Then add something like this to your OnSuccess handler in javascript:
Javascript
function anOnSuccessFunction (data)
{
if (data.success == true)
{
window.location = data.redirecturl;
}
}
Markup
Make sure you point your Ajax options to the javascript function.
xPost.OnSuccess = "anOnSuccessFunction";

How to update the database table in button click?

I am working on the MVC3 with ADO.Net Connectivity, an then i am updating the div with jQuery
Here i my code
Controller
public ActionResult GetData()
{
return this.Json(_db.MYMOVIELISTs, JsonRequestBehavior.AllowGet);
}
public void Insert(string Id)
{
var movieToInsert = new MYMOVIELIST { Title = "Ben", Director = "LEMe", ID = Id };
// Save new movie to DB
_db.AddToMYMOVIELISTs(movieToInsert);
_db.SaveChanges();
}
ClientSide
function insertCallback(result) {
readData();
}
function readData() {
info.empty();
$.ajax({
type: "GET",
url: 'Home/GetData',
async: false,
success: function (data) {
for (var i = 0; i < data.length; i++) {
var panel = $("<div class='panel' ></div>")
var d = data[i];
panel.append("ID: " + d.ID + "</br>");
panel.append("Title: " + d.Title + "</br>");
panel.append("Director: " + d.Director + "</br>");
panel.append("<hr>");
panel.data("info", d);
panel.appendTo(info);
}
}
});
}
$("#btnAdd").click(function () {
$.post("Home/Insert", $("form").serialize(), insertCallback);
});
This is works Fine, my problem is i want to update the Database table in "Save" buttom click. i tried to call the _db.SaveChanges(); in save button click instead of the Insert it is not adding the movieToInsert to table, here i want to know is how to save the database later, Here any thing am doing wrong or is there any best approach for DB connectivity
You are serializing a form, so eventually you may want below... which will bind your serialized form to the a movie model/entity:
[AcceptVerbs("POST")]
public void Insert(MovieEntity movie)
As for database practice, I recommend reading about the repository pattern and dependency injection as it pertains to ASP.NET MVC.

How to return IEnumerable values with using ajax in MVC3?

How can I return IEnumerable's values with using ajax. Here is my script:
$.ajax({
type: "get", url: "street", data: { a: value2 },
success: function (data) {
alert(data);
}
And here is my controller method:
[HttpGet]
public string street(string a)
{
EmlakServicesClient client = new EmlakServicesClient();
client.ClientCredentials.UserName.UserName = "service_test";
client.ClientCredentials.UserName.Password = "..";
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
Street[] list =client.GetStreet(Convert.ToInt32(a));
return ("" + list.FirstOrDefault().StreetName);
}
As you can see at top I get value but with First Value so how can I get these all values from IEnumarable?
You should use JSON:
return Json(list, JsonRequestBehavior.AllowGet);
You will need to change your action method to return ActionResult.
return the Collection as JSON
public ActionResult GetsomeItems(int someId)
{
var someCollection=GetListOfItemsFromSomeWhere(someId)
return Json(someCollection,JsonRequestBehaviour.AllowGet);
}
I tripped over this while doing a Google search on how to return JSON results using ASP.NET Web API 2. In case someone else is looking for the same solution, here is the solution that worked for me:
// GET: api/Users
public HttpResponseMessage Get()
{
var users = UserManager.Get(); // returns IEnumerable
return Request.CreateResponse(HttpStatusCode.OK, users);
}
You can learn more about HttpResponseMessage here.

Resources