Firstly, I'm beginner of the MVC.
I have a controller named FinanceController. I have two views named StoreEvaluationForm and SendStoreEvaluationToPdf of this control. I want to call a first view's public static function, which is defined in #functions, from second view.
I guess views have hidden class in mvc. Because I realized when I mouse over first view's function, VS shows its class named _Page_Views_Finance_StoreEvaluationForm_cshtml and its namespace named ASP. However I couldn't find any way to accessing another view's function. In second view ASP namespace has only its class named _Page_Views_Finance_SendStoreEvaluationToPdf_cshtml.
To be clear, function in the view is a C# function not a javascript function. Its definition is:
#functions
{
public static string NumberFormatter(double? number, bool percent = false)
{
return number == null ? null : string.Format("{0}{1}", number.Value.ToString("N2"), percent ? "%" : null);
}
}
Yes, this can be achieved. I tried it with the default MVC project in Visual Studio 2015.
Content of About view:
#{
ViewBag.Title = "About";
}
#functions
{
public static string DoStuff()
{
return "Content from About view.";
}
}
Content of Index view:
#{
ViewBag.Title = "Home Page";
}
#_Page_Views_Home_About_cshtml.DoStuff()
... (other stuff)
In Index view there is a red squiggly line below _Page_Views_Home_About_cshtml displaying :
The name _Page_Views_Home_About_cshtml does not exist in the current context
Despite the error message, the application builds successfully and I can see the message from the About view when navigating to /Home/Index.
Related
Below I have attached my code. I'm simply trying to create a view for this page but I continue to get this error. I have already inherited this controller from controller base, yet I'm still getting this error. (Red squiggle line under View) Saying the name "View" does not exist in this current context. I have also created a View folder with a page called Index. Can someone help me with this?
namespace EmptyCore.Controller
{
public class HomeController : ControllerBase
{
private IBookRepository _bookRepository;
public HomeController(IBookRepository bookRepository)
{
_bookRepository = bookRepository;
}
public ViewResult Index()
{
//Book book = _bookRepository.GetBook(1);
//return new ObjectResult(book);
return View();
}
}
}
There is an easy way to make a view.
In your method Index you can right click "View();
Then you press Add View.
This is an easier way to make a view. Maybe that way it might work for you.
You don't have to make your own folders.
I have a cshtml view and in there I have used Model. But the problem is that model shows in my View.
#Model LMM.NEWS.Documents;
#{
Layout = null;
ViewBag.Title = "News Doc Download";
}
In my view, It shows me in the text like below. How to solve this?
System.Collections.Generic.List`1[LMM.Entities.DTO.NEWS.Documents] LMM.Entities.DTO.NEWS.Documents;
Here i have attached,my model shows in text in my view
Is because of this line:
#Model LMM.NEWS.Documents;
it's calling the toString(); method from Object, one solution is to override toString(); on your Documents class:
public override string ToString()
{
return string.Empty;
}
Not completely sure if that fixes your problem because I don't have a project to test it out, but you could try.
My first go with Razor Pages inline markup. Running into this weird issue after passing a ViewModel to a PartialView.
Of course in my parent page I pass the ViewModel to the PartialView:
#{Html.RenderPartial("Partial/_RequestView", Model.NewRequest);}
public class IndexModel : PageModel
{
private readonly IActiveDirectoryClient _activeDirectoryClient;
private readonly ITravelClient _travelClient;
public IEnumerable<TravelRequestViewModel> Requests { get; set; }
In the partial view, I have no issue referencing the model in a lambda expression
#Html.HiddenFor(model => model.RequestId)
However when I attempt to reference the Model in razor markup inline the Model is null. Any ideas?
<p>#Model.Name</p>
The NewRequest property is set within the OnGetAsync() method in the parent page
public async Task<IActionResult> OnGetAsync()
{
NewRequest = BuildNewRequest();
if (NewRequest == null)
throw new NullReferenceException("Unable to build new travel request");
return await Task.FromResult(Page());
}
Answered my own question. MUST remove the #page directive in order for the partial view to work and for the #Model to be recognized.
Kinda bizarre that VS 2017 templates adds this directive for a partial view, I can only assume it's a bug.
I have following scenario:
My Index page, uses a layout which has a partial View ebbeded in it. the partial view contains a search text box.
For a particular scenario, i need to set the text of the search box with my viewdata[] for index page.
is it somehow poosiblein mvc3, asp.net 2010 to set the value of textbox in partial view from the viewpage?
You could make your partial strongly typed to some view model:
#model SearchViewModel
#using (Html.BeginForm())
{
#Html.LabelFor(x => x.Keywords)
#Html.EditorFor(x => x.Keywords)
<button type="submit">OK</button>
}
and then when inserting the partial you could pass this view model:
#Html.Partial("_Search", new SearchViewModel { Keywords = "some initial value" })
or even better the view model of your main view will already have a property of type SearchViewModel and you will be able to call the partial like this:
#Html.Partial("_Search", Model.Search)
Now obviously in your Index action you no longer need to use any ViewData, but you could directly work with your strongly typed view model:
public ActionResult Index()
{
var model = new MyViewModel
{
Search = new SearchViewModel
{
Keywords = "some initial value"
}
};
return View(model);
}
You can always make the partial view strongly typed (even if the model is just a string) and pass the value you need.
public class MyModel
{
public int ValueForView {get;set;}
public string TextBoxValue {get;set;}
}
-Index.cshtml
#model MyModel
#{ Html.RenderPartial("PartialView", Model.TextBoxValue); }
-PartialView.cshtml
#model string
#Html.TextBoxFor(m => Model)
As I understand your issue, the partial view is in your layout and you need to get data into it.
In this case layouts are processed last but passing data to it your options are somewhat limited. You can use an ActinFilter or ViewData.
ViewData is the easiest, and also the messiest so I don't recommend it.
ActionFilters would work, but you could just process your partial by simply calling in your layout:
#Html.RenderAction("PartialViewAction", "PartialViewController")
Unless I'm missing something I don't believe the other answers addressed that this is in a layout, hence a different issue.
How to write a code for displaying the alert message: "Successfully registered", after user data is stored in database, using MVC
I am using Asp.Net MVC3, C#, Entity Model.
Try using TempData:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
#if (TempData["notice"] != null) {
<p>#TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.
Having said that it would be possible to trigger an alert from the controller code by doing something like this -
public ActionResult ActionName(PostBackData postbackdata)
{
//your DB code
return new JavascriptResult { Script = "alert('Successfully registered');" };
}
You can find further info in this question - How to display "Message box" using MVC3 controller
Personally I'd go with AJAX.
If you cannot switch to #Ajax... helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
#using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
#{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('#Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('#Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
#Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.
Little Edit
Try adding
return new JavascriptResult() { Script = "alert('Successfully registered');" };
in place of
return RedirectToAction("Index");