Iframe Src from controller - asp.net-mvc

I have an Iframe in a view that i need to populate the src from my controller This is the part of the controller that it has to be called from.
else
{
//TODO: add after mobile detection is added back in
//if (Request.Browser.IsMobileDevice)
// return RedirectToAction("Index", "Mobile", new { Area = "" });
//else
return RedirectToAction("Index", "Home", new { Area = "" });
}
I know this is how youwould do it if it wasnt in MVC so how could i call my iframe from the controller?
ifr1.Attributes["src"] = "http://localhost:8000/index.php/login/?u=" + Session["username_s"] + "&p=" + Session["password_s"];
enter code here

You can use ViewData or ViewBag for this purpose.
In your controller you should have the following:
else
{
//TODO: add after mobile detection is added back in
//if (Request.Browser.IsMobileDevice)
// return RedirectToAction("Index", "Mobile", new { Area = "" });
//else
ViewBag.IframeUrl = "http://localhost:8000/index.php/login/?u=" + Session["username_s"] + "&p=" + Session["password_s"];
return RedirectToAction("Index", "Home", new { Area = "" });
}
In you View you can use the following:
<iframe src="#(ViewBag.IframeUrl)"></iframe>
You can also use ViewData by replacing ViewBag.IframeUrl with ViewData["IframeUrl"]

You should use ViewBag in the target action, passing the URL, for exemple:
1) Your target redirect action should look like:
public ActionResult Index()
{
//Other code from the action here
ViewBag.IFrameSrc = "http://localhost:8000/index.php/login/?u=" + Session["username_s"] + "&p=" + Session["password_s"];
return View();
}
2) The Index View should look like:
<iframe src="#ViewBag.IFrameSrc">
</iframe>

Related

How to redirect user to action inside another controller

I try to write a method that when call it user redirect to action inside another controller. I use return Redirect("~/" + redirectUrl + "/" + paymentInfo.ObjectIdDepartue); statment for do this. and test type of this method by RedirectResult , ActionResult but dont work.
What is problem?
public RedirectResult PayViaCredit(int paymentId)
{
var paymentInfo = db.Payments.Find(paymentId);
//Decrease Credit
Profile userProfile = _utility.GetProfileOfUser();
decimal decreasedCredit = userProfile.Credit - paymentInfo.Price using (var transactionScope = new TransactionScope())
{
try
{
db.ProcUpdateProfileCredit(decreasedCredit, userProfile.UserId);
//Update Payment
paymentInfo.Transactionsuccess = true;
paymentInfo.state = 3;
paymentInfo.Confirmed = true;
db.Entry(paymentInfo).State = EntityState.Modified;
db.SaveChanges();
System.Web.HttpContext.Current.Session["InvoiceNumber"] = paymentInfo.Id.ToString();
transactionScope.Complete();
}
catch (Exception e)
{
_errorLog.Error("CreditPayment.cs/PayViaCredit", "", e.Source, "Message:::" + e.Message + "---InnerException:::" + e.InnerException);
transactionScope.Dispose();
}
}
string redirectUrl = _creditPayment.GetRedirectUrlCreditPayment(paymentInfo);
return Redirect("~/" + redirectUrl + "/" + paymentInfo.ObjectIdDepartue);
}
public ActionResult AfterPaymentBank()
{
return View();
}
First of all keep your data in TempData.
TempData["myData"] = paymentInfo.ObjectIdDepartue;
Then
return Redirect("/ControllerName/ActionName");
What ever is your redirectUrl , give it a shape like this.
TempData["myData"] = paymentInfo.ObjectIdDepartue;
redirectUrl = redirectUrl.Substring(1); // or what ever you thing appropriate for your URL
return Redirect(redirectUrl);
Now inside "ActionName" action method , type cast your TempData to your desire type.
public ActionResult ActionName()
{
var myData=(myType)TempData["MyData"];
// and proceed....
}

MVC Controller return RedirectToAction Id + #id

Hello im trying to redirect the user to the blog section and it works fine but i want the user to land on bottom of site section ( #section-variants )
but i cant figure out what im doing wrong is there any other way of passing it along
public ActionResult BlogComment_Delete(int? id, int? postid)
{
if (id.HasValue)
{
Notification model = db.Notifications.Find(id.Value);
if (model != null)
{
db.Notifications.Remove(model);
db.SaveChanges();
}
}
return RedirectToAction("BlogPost", "Blog", new { Id = postid + "#section-variants" });
}
You should use another method - RedirectResult:
return new RedirectResult(Url.Action("BlogPost", "Blog", new { Id = postid }) + "#section-variants");

Alter does not working before redirect + controller MVC

I have code:
public ActionResult Inner(simpleQA.Models.Post model)
{
if(simpleQA.User.Current != null)
{
simpleQA.Post objPostAns = new Post();
objPostAns.TypeId = 4;
objPostAns.Content = model.ContentAnswesr;
objPostAns.RelatePostId = model.RelatePostId;
objPostAns.CreateAt = DateTime.Now;
objPostAns.CreateBy = simpleQA.User.Current.Id;
objPostAns.Save();
return View("");
}
else
{
Response.Write("Please Login");
Response.Redirect("/");
}
return View("/");
}
I try Respon.write alter before redirect but it does not working.
Tell me one alter.
You can't use response.write in an MVC controller. The controller can only pass data to the view.
What you should do instead of Response.Redirect is redirect to a login View:
return RedirectToAction("Login");
(better use built in (forms)authentication because it'll send the user to the login form automatically and after login back to the page he meant to go to)

MVC ASP.NET - Redirect to anchor with model state

The following code redirects to a view with the anchor and works. However I need to send the model state through for validation and I am not sure how to do that while using a redirect. I want to set the model error to populate the validation summary.
[HttpPost]
public ActionResult Send(QuoteModel model, string CatchAll)
{
try
{
if (ModelState.IsValid)
{
}
else
{
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
return Redirect(Url.RouteUrl(new { controller = "Home", action = "Index"}) + "#quote");
}
}
catch
{
return View();
}
}
I think you can't do it this way, try to add an additional parameter for your action to determine if the error occurs
return Redirect(Url.RouteUrl(new { controller = "Home", action = "Index"}) + "?modelerror=true" + "#quote");
and check this url parameter in your action.

Get the Current ViewContext in ASP.Net MVC

I have a ASP.Net MVC JsonResult function in which I want to return the contents of a PartialView (The content has to be loaded using Ajax, and for some reason I can't return a PartialViewResult).
To render the PartialView I need the ViewContext object.
How do you get the current ViewContext object within an Action method? I don't even see HttpContext.Current in my action method.
I am using ASP.net MVC 1.
a ViewContext is not available within the action method because it is constructed later before rendering the view. I would suggest you using MVCContrib's BlockRenderer to render the contents of a partial view into a string.
I may have missed a point somewhere but my Actions that returned partial views do so by returning a View object that refers to an ascx page. This will return partial HTML without the full page constructs (html, head, body, etc.). Not sure why you'd want to do anything beyond that, is there a specific reason you need to return PartialViewResult? Here's an example from my working code.
First the Action in my controller:
public ViewResult GetPrincipleList(string id)
{
if (id.Length > 1)
id = id.Substring(0, 1);
var Principles = competitorRepository.Principles.Where(p => p.NaturalKey.StartsWith(id)).Select(p=>p);
return View(Principles);
}
And then the partial view (ascx):
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<MyProject.Data.Principle>>" %>
<% foreach (var item in Model) { %>
<div class="principleTitle" title="<%= Html.Encode(item.NaturalKey) %>"><%= Html.Encode(item.Title) %></div>
<%} %>
Lastly, the Jquery that sets up the call:
$(function() {
$(".letterSelector").click(function() {
$("#principleList").load("/GetPrincipleList/" + $(this).attr("title"), null, setListClicks);
});
});
So, a full AJAX process, hope that helps.
---- UPDATE following comment ----
Returning Json data is just as easy:
Firstly, initiating the AJAX call when a select box changes:
$("#users").change(function() {
var url = "/Series/GetUserInfo/" + $("#users option:selected").attr("value");
$.post(url, null, function(data) { UpdateDisplay(data); }, 'json');
});
The javascript that processes the returned json data:
function UpdateDisplay(data) {
if (data != null) {
$("div.Message").fadeOut("slow", function() { $("div.Message").remove(); });
$("#Firstname").val(data.Firstname);
$("#Lastname").val(data.Lastname);
$("#List").val(data.List);
$("#Biography").val(data.Biography);
if (data.ImageID == null) {
$("#Photo").attr({ src: "/Content/Images/nophoto.png" });
$("#ImageID").val("");
}
else {
if (data.Image.OnDisk) {
$("#Photo").attr({ src: data.Image.ImagePath });
}
else {
$("#Photo").attr({ src: "/Series/GetImage?ImageID=" + data.ImageID });
}
$("#ImageID").val(data.ImageID);
}
$("form[action*='UpdateUser']").show();
} else {
$("form[action*='UpdateUser']").hide();
}
};
And finally the Action itself that returns the json data:
public JsonResult GetUserInfo(Guid id)
{
MyUser myuser = (from u in seriesRepository.Users
where u.LoginID == id
select u).FirstOrDefault();
if (myuser == null)
{
myuser = new MyUser();
myuser.UserID = 0;
myuser.Firstname = Membership.GetUser(id).UserName;
myuser.Lastname = "";
myuser.List = "";
myuser.Biography = "No yet completed";
myuser.LoginID = id;
}
return Json(myuser);
}
Does that help? If not then can you post some of the code you are working on as I'm missing something.

Resources