MVC ViewBag for partial view is null - asp.net-mvc

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")

Related

Display MVC message on start running

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>

The partial view 'First.cshtml' was not found or no view engine supports the searched locations

I'm trying to call partial view in div on click. I've written this:
#Ajax.ActionLink("Second", "Second", new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "partials",
InsertionMode = InsertionMode.Replace
})
<div id="partials">
</div>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/5.2/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
In my Index.cshtml. my controller looks like this:
public ActionResult Index()
{
return View();
}
public PartialViewResult Second()
{
return PartialView("Second.cshtml");
}
but my error says that my partial view can't found in:
~/Views/switchPartial/Second.cshtml.aspx
~/Views/switchPartial/Second.cshtml.ascx
~/Views/Shared/Second.cshtml.aspx
~/Views/Shared/Second.cshtml.ascx
~/Views/switchPartial/Second.cshtml.cshtml
~/Views/switchPartial/Second.cshtml.vbhtml
~/Views/Shared/Second.cshtml.cshtml
~/Views/Shared/Second.cshtml.vbhtml
but I have it in switchPartial folder.
If I write #Html.Partial("Second") in my div it renders correctly my partial view.
What have I done wrong?
No need to include the file extension at the end of the partial name. Try:
return PartialView("Second");
By not including the file extension, each of the registered ViewEngines is given its opportunity to resolve the requested view (be in Second.cshtml, Second.vbhtml or Second.aspx).

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.

Why can't I HtmlDecode in ASP.NET MVC 3

Here is the scenario. I want to use CKEditor for a rich text field on a form, but for whatever reason I cannot get the contents from the textarea to the server and back to the page without encoding problems. Here is the little sample program I wrote up to try and figure out what is going on. First, my view model:
HomeViewModel.cs
namespace CkEditorTest.Models
{
public class HomeViewModel
{
[Required]
[DataType(DataType.Html)]
[Display(Name = "Note")]
public string Note { get; set; }
}
}
Now my controller:
HomeController.cs
using System.Web.Mvc;
using CkEditorTest.Models;
namespace CkEditorTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new HomeViewModel());
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(HomeViewModel model)
{
return View(model);
}
}
}
And finally, my view:
Index.cshtml
#model CkEditorTest.Models.HomeViewModel
#{
ViewBag.Title = "CKEditor Test";
}
#section head
{
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/ckeditor.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/ckeditor/adapters/jquery.js")"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Note").ckeditor();
});
</script>
}
<h2>CKEditor Test</h2>
#using (Html.BeginForm())
{
#Html.LabelFor(m => m.Note)<br /><br />
#Html.TextAreaFor(m => m.Note)<br />
<input type="submit" />
}
#if (!String.IsNullOrEmpty(Model.Note))
{
<div id="noteText">#Model.Note</div>
}
No matter what I do, I cannot display the Model.Note property as html on my view. By the time it reaches the view it is HTML encoded (i.e. <p> etc...). Here is what the form looks like pre-post:
pre-post http://www.matthewkimber.com/images/so/pre-post.png
And here is what the result is in the div below the "Submit" button:
post result http://www.matthewkimber.com/images/so/posted.png
I've set a breakpoint within Visual Studio and it shows as bare angle brackets (no encoding on HTML elements, just characters).
breakpoint results http://www.matthewkimber.com/images/so/dataInsideTheActionMethod.png
This, of course, is the stripped down test. I've tried encoding it, decoding it both in the view and in the controller to no avail.
By default everything is encoded when you use razor. I think you're looking for the Raw method.
It would also be a good idea to check the response using Fiddler or Firebug.
Try this:
#Html.DisplayTextFor(modelItem => item.Note)
You can also use HtmlString("")

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