Display MVC message on start running - asp.net-mvc

Im writing a script, i want to display a message to the view and then start my action. But its not showing anything, because my executing is blocking my startmessage. I dont want to use jquery/javascript.
Im trying this in my home/index controller
return View(model: "Synck started, " + DateTime.Now.ToString("yyyy-MM-dd
HH:mm:ss"));
In my view
<div id="txt">
#Model // Synck started, 2015-10-10 10:10:10
#Html.Action("Start", "Home")
</div>

This worked for me...
The Controller::
// GET: Home/Index
public ActionResult Index()
{
ViewBag.Message = "Synck started, " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
return View();
}
The View:
#ViewBag.Message

Ideally what you should be doing is keeping your long running code to a separate method and asynchronously invoke it from your UI. You may use jQuery ajax to do this.
public ActionResult Index()
{
return View();
}
public ActionResult SyncMydata()
{
//Execute your long running code here and return something as needed.
}
And in your Index view,
<div id="status"></div>
<script type="text/javascript">
$(function(){
var url="#Url.Action("SyncMydata","Home")";
$("#status").html("Started syncing at "+new Date().toLocaleString());
$.post(url,function(res){
$("#status").html("Sync completed"));
});
});
</script>
If you want, you can get the start time from the Index action(server side) rather than using the javascript time.

You can try to send the message that you want to display and ready for ViewData
Your Controller :
controllerName ()
{
ViewData["Message"] ="Synck started, " + DateTime.Now.ToString("yyyy-MM-dd
HH:mm:ss";
return View();
}
Your View:
<div id="txt">
#ViewData["Message"] // Synck started, 2015-10-10 10:10:10
#Html.Action("Start", "Home")
</div>

Related

MVC ViewBag for partial view is null

Have a basic question regarding partial view.the #ViewBag.Message comes out empty in the final render.
My controller looks like this
public ActionResult Message() {
ViewBag.Message = "This is a partial view.";
return PartialView();
}
public ActionResult PartialViewDemo() {
return View();
}
My partial view looks like this in Message.cshtml
<h2>#ViewBag.Message</h2>
I am calling the partial view like this from partialViewTest.cshtml. the #ViewBag.Message is empty and only h2 tag is shown.
<div>#Html.Partial("~/Views/Sample/Message.cshtml")</div>
If i implement using javascript it works fine
<div id="result"></div>
#section scripts {
<script type="text/javascript">
$(function () {
$('#result').load('/sample/message');
});
</script>
}
You Render Message.cshtml only (not controller) from partialViewTest.cshtml. As you set ViewBag.Message in the controller, you have to call the controller (to get partial view) like this.
#Html.Action("Message", "Sample")

MVC return View not calling controller

I'm extremely new to MVC, but am battling with an issue that is probably very basic and obvious.
On my HomeController, I have:
[HttpGet]
public ViewResult Index()
{
int hour = DateTime.Now.Hour;
var reply = User.Identity.IsAuthenticated ? User.Identity.Name + " is Logged in!" : hour < 12 ? "Good morning" : "Good afternoon";
ViewBag.Greeting = reply;
return View();
}
When I start my application, this code runs.
The page as a link to a Login screen.
<div>
#Html.ActionLink("Login", "ShowLoginScreen")
</div>
The page loads, and the user logs in.
The login cshtml file loads, and the user has a username/password to enter:
<body>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
<p>Username: #Html.TextBoxFor(x=>x.Username)</p>
<p>Password: #Html.TextBoxFor(x=>x.Password)</p>
<p><input type="submit" value="Login"/></p>
}
</body>
When clicking Login, it calls a method in my HomeController:
[HttpPost]
public ActionResult ShowLoginScreen(Login login)
{
if (ModelState.IsValid)
{
var reply = new BasicFinanceService.UserService().Authenticate(login.Username,
Security.EncryptText(login.Password));
if(reply.Id != 0)
FormsAuthentication.SetAuthCookie(reply.Username, false);
return View("Index");
}
return View();
}
The code runs, it goes back to Index, BUT the method in the Home Controller for 'Index' doesn't run. The page just gets rendered without any breakpoint in my "public ViewResult Index()" being called.
Can anyone tell me where I am going wrong?
It's because you're simply returning the output of the view with:
return View("Index");
That doesn't actually invoke the controller action, it simply returns the view. To do what you want, you need to use RedirectToAction:
return RedirectToAction("Index");

Action returns PartialView rather than View

I've simplified the below for brevity.
When I click the actionlink, the action works successfully but returns only the partial view on it's own page rather than rendering it within the view. Any suggestions where I am going wrong?
PartialView ActionLink
#Html.ActionLink("Click", "_Partial1")
Controller
public ActionResult Index()
{
return View()
}
public ActionResult _Partial1()
{
...do stuff
return PartialView();
}
You can use the "Click" as below. Make sure you have reference to jQuery
<script type="text/javascript" src="/Scripts/jquery-1.8.2.min.js"></script>
Modify your Action Link as below.
#Html.ActionLink("Click", // linkText
"_Partial1", // actionName
null, // controllerName
new { #class = "detailsLink" } // htmlAttributes
)
Provide a element where you want to render the content.
< div id="details" />
Invoke the below JS, so the content will be loaded in the view or similar.
$(function() {
$('.detailsLink').click(function() {
$('#details').load(this.href);
return false;
});
});
This should invoke you partial action and renders the content on the same page.

MVC 3 StackOverflowException w/ #Html.Action()

I've looked over a bunch of other reports of this, but mine seems to be behaving a bit differently. I am returning PartialViewResults for my child actions, so that's not the source of the recursion. Here's a dumbed down version of what I have.
// The Controller
[ChildActionOnly]
public ActionResult _EditBillingInfo()
{
// Generate model
return PartialView(model);
}
[HttpPost]
public ActionResult _EditBillingInfo(EditBillingInfoViewModel model)
{
// Update billing informatoin
var profileModel = new EditProfileViewModel()
{
PartialToLoad = "_EditBillingInfo"
};
return View("EditProfile", profileModel);
}
[ChildActionOnly]
public ActionResult _EditUserInfo()
{
// Generate model
return PartialView(model);
}
[HttpPost]
public ActionResult _EditUserInfo(EditUserInfoViewModel model)
{
// Update user informatoin
var profileModel = new EditProfileViewModel()
{
PartialToLoad = "_EditUserInfo"
};
return View("EditProfile", profileModel);
}
public ActionResult EditProfile(EditProfileViewModel model)
{
if (String.IsNullOrEmpty(model.PartialToLoad))
{
model.PartialToLoad = "_EditUserInfo";
}
return View(model);
}
// EditProfile View
#model UPLEX.Web.ViewModels.EditProfileViewModel
#{
ViewBag.Title = "Edit Profile";
Layout = "~/Views/Shared/_LoggedInLayout.cshtml";
}
<div>
<h2>Edit Profile</h2>
<ul>
<li class="up one"><span>#Ajax.ActionLink("Account Information", "_EditUserInfo",
new AjaxOptions { UpdateTargetId = "EditProfileDiv", LoadingElementId = "LoadingImage" })</span></li>
<li class="up two"><span>#Ajax.ActionLink("Billing Information", "_EditBillingInfo",
new AjaxOptions { UpdateTargetId = "EditProfileDiv", LoadingElementId = "LoadingImage" })</span></li>
</ul>
<img alt="Loading Image" id="LoadingImage" style="display: none;" src="../../Content/Images/Misc/ajax-loader.gif" />
<div id="EditProfileDiv">
#Html.Action(Model.PartialToLoad)
</div>
</div>
The partial views are both forms for updating either the user information or billing information.
I debugged through this and found what is happening, but cannot figure out why. When a user browses to EditProfile, it load up with the _EditUserInfo partial and the form is there for editing. When you change some info and submit the form it hangs and you get a StackOverflowException in the EditProfile view on the call to #Html.Action(). What happens is on the initial visit to EditProfile, the #Html.Action calls the HttpGet version of _EditUserInfo. You make some changes to the user info and click submit. Once the information is updated the EditProfile view is returned again, but this time #Html.Action calls the HttpPost version of _EditUserInfo which updates the user information again, returns the EditProfile view again and the #Html.Action calls the HttpPost version of _EditUserInfo... You get where this is going. Why after form submission does it call the post version and not the get version like it did for the initial visit to EditProfile?
Thanks for any help!
I might be getting this a bit wrong, it's been a long day so, but in EditProfile you set PartialToLoad (if it's empty) to "_EditUserInfo", then in _EditUserInfo you set it again to _EditUserInfo, won't this create a loop that behaves as what you are experiencing?

How do you close an ASP.NET MVC page from the controller?

I have an ASP.NET MVC app that opens a "Request" view in a new browser window. When the user submits the form, I'd like the window to close. What should my RequestController code look like to close the window after saving the request information? I'm not sure what the controller action should be returning.
You could return a View that has the following javascript (or you could return a JavaScript result) but I prefer the former.
public ActionResult SubmitForm()
{
return View("Close");
}
View for Close:
<body>
<script type="text/javascript">
window.close();
</script>
</body>
Here is a way to do it directly in your Controller but I advise against it
public ActionResult SubmitForm()
{
return JavaScript("window.close();");
}
Like such:
[HttpPost]
public ActionResult MyController(Model model)
{
//do stuff
ViewBag.Processed = true;
return View();
}
The view:
<%if(null!=ViewBag.Processed && (bool)ViewBag.Processed == true){%>
<script>
window.close();
</script>
<%}%>
It sounds like you could return an almost empty View template that simply had some javascript in the header that just ran "window.close()".
You can close by this code:
return Content(#"<script>window.close();</script>", "text/html");
This worked for me:
[HttpGet]
public ActionResult Done()
{
return Content(#"<body>
<script type='text/javascript'>
window.close();
</script>
</body> ");
}
This worked for me to close the window.
Controller:
return PartialView("_LoginSuccessPartial");
View:
<script>
var loginwindow = $("#loginWindow").data("kendoWindow");
loginwindow.close();
</script>
Using this you can close the window like this:
return Content("<script language='javascript'>window.close();</script>");

Resources