MVC razor view - Stop c# code compilation - c#

I have a razor view showing details of a Hotel.
model for the view:
#model MySite.MyViewModels.Hotel
Have to show many details segments of the hotel. So, I have to check null for the Model on each segment. Is it possible if I can check once for all and stop the compilation of c# code if it is null.
You can say on top of the view If I can write something like:
#If(Model==null || Model.RoomsAvailable.Count<1)
{
//Don't read c# code on rest of the view now
}
Hope it make sense.

In your controller:
pubilc ActionResult YourAction()
{
if (null == YourModel)
{
return View(SomeEmptyView); // or return null
}
return View(Some legitimate view);
}
By that, you don't need to add logic to your view and you get what you wanted.

Related

Display Each Element From Array Using HTML Helper in C#

This is probably a very simple problem, but I am extremely new to C# / MVC and I have been handed a broken project to fix. So it's time to sink or swim!
I have an array of strings that is being passed from a function to the front end.
The array looks something like
reports = Directory.GetFiles(#"~\Reports\");
On the front end, I would like it to display each report, but I am not sure how to do that.
This project is using a MVC, and I believe the view is called "Razor View"? I know that it's using an HTML helper.
In essence, I need something like
#HTML.DisplayTextFor(Model.report [And then print every report in the array]);
I hope that makes sense.
If you want to display the file name array you can simply use a foreach:
#foreach(var report in Model.Reports){ #report }
Note that you should add the Reports property to your view model:
public class SampleViewModel
{
public string [] Reports { get; set; }
}
You could use ViewData or TempData but I find that using the view model is the better way.
You can then populate it:
[HttpGet]
public ActionResult Index()
{
var model = new SampleViewModel(){ Reports = Directory.GetFiles(#"~\Reports\")};
return View(model);
}
And use it in the view as you see fit.
Here is a simple online example: https://dotnetfiddle.net/5WmX5M
If you'd like to add a null check at the view level you can:
#if(Model.Reports != null)
{
foreach(var report in Model.Reports){ #report <br> }
}
else
{
<span> No files found </span>
}
https://dotnetfiddle.net/melMLW
This is never a bad idea, although in this case GetFiles will return an empty list if no files can be found, and I assume a possible IOException is being handled.

ASP.NET MVC controller sends data to view but 'ThenInclude' data in view is null

In my controller I am using .Include and .ThenInclude to fill my object.
When I debug and view the properties of the servicePackage, I can see all of the data I expect to see is there:
ServicePackage servicePackage = await _context.ServicePackage
.Include(bs => bs.ServicePackageLines)
.ThenInclude(bsl => bsl.Product)
.Where(bs => bs.Id == id)
.FirstOrDefaultAsync();
// viewing the properties of this servicePackage
// shows that there is product data when I drill down.
return View(servicePackage);
But in the view I cant access the data:
#model Domain.Entities.ServicePackage
#foreach (var lineDetail in Model.ServicePackageLines)
{
#if(lineDetail.Product != null)
{
<td>#lineDetail.Product.SupplierModelNumber</td>
}
else
{
<td>#lineDetail.ProductId</td>
}
}
Always shows the line detail product Id, and not the model number.
I'm not sure what I'm doing wrong, but it would be great if someone could put me on the right path.

creating dynamic views at runtime asp.net mvc

I'm fairly new to mvc, and have started learning asp.net mvc 5 and django
I want to create an application where the user can create a new view at runtime. So lets say I create a feature in the web app for a user to add a new page where they can fill out a form, say the title maybe text, or fields they want to display on the view, and when the user saves it that info gets saved to the db and creates a new view.
My questions are:
can you create dynamic views at runtime?
how do you create the proper url to route to that new page?
if the 1st two are possible can you use a model or viewModel to then display the content from the db for that page?
Any advice on if this can be done would be appreciated. Thanks
I think you need to make a page that saves the user configuration in db as per user demand.
From my end, I suggest the following approach to do it.
Whatever you gets the data from database which are returns like as below snap.
Make one Action in controller and assign those data in one datatable/list in action.
public ActionResult LoadContent()
{
dynamic expando = new ExpandoObject();
var model = expando as IDictionary<string, object>;
/*Let say user insert the detail of employee registration form. Make the
database call and get the distinct detail of particular inserted form by Id
or whatever. As an example below datatable contains the data that you fetch
during database call.*/
DataTable objListResult =
HeaderViewActionHelper.GetFinalResultToRenderInGenericList(id);
if (objListResult != null && objListResult.Rows.Count > 0)
{
foreach (DataRow row in objListResult.Rows)
{
model.Add(row["DisplayName"].ToString(),
row["DisplayNameValue"].ToString());
/*If you want to handle the datatype of each field than you can bifurcation
the type here using If..else or switch..case. For that you need to return
another column in your result from database i.e. DataType coloumn. Add in
your model as, model.Add(row["DisplayName"].ToString(),
row["DisplayNameValue"].ToString(), row["DataType"].ToString());*/
}
}
/* return the model in view. */
return View(model);
}
In the view you can go through the loop over modal and render the detail.
#model dynamic
#using (Html.BeginForm("SubmitActionName", "ControllerName")
{
<div class="table-responsive">
<table>
#if (Model != null)
{
foreach (var row in Model)
{
}
}
</table>
</div>
}
For more detail, Please go through this link.

add logic to _ViewStart.cshtml

is there a way to add logic in the _ViewStart.cshtml file to drive which _Layout file to use?
Conceptually, I want to do the code below (ViewBag.Context is determined in the Home controller). But I get a red squiggly under ViewBag (does not exist in current context). I guess this is a problem because this view page doesn't know which controller/method is calling it.
#{if (ViewBag.Context == "AA")
{
Layout = "~/Views/Shared/_Layout_AA.cshtml";
}
else
{
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
FWIW, you can also do this in the controller:
if (someCondition == "AA")
{
return View("MyView", "~/Views/Shared/_Layout_AA.cshtml");
}
else
{
return View ("MyView", "~/Views/Shared/_Layout.cshtml");
}
Use the PageData property (it's something more applicable to ASP.NET WebPages and seldom used in MVC)
Set:
#{
PageData["message"] = "Hello";
}
Retrieve
<h2>#PageData["message"]</h2>
Source: How do I set ViewBag properties on _ViewStart.cshtml?
Use a ternary operator:
#{
Layout = ViewBag.Context == "AA" ? "~/Views/Shared/_Layout_AA.cshtml" : "~/Views/Shared/_Layout.cshtml" ;
}
Some of you are not seeing "But I get a red squiggly under ViewBag (does not exist in current context). I guess this is a problem because this view page doesn't know which controller/method is calling it."
My solution was to embed the value in a cookie while in the controller at the start. Then in the _ViewStart.cshtml file, I retrieve the cookie value and can now use it to dictate my layout logic.

In MVC Edit Action {HTTP POST} Using UpdateModel vs Request.Form Collection

I am working through sample MVC Nerdinner tutorial and using it on the AdventureWorks database. I have created an Edit action in the CategoryController to edit Product Category in AdventureWorks. The only updateable field in this table is the Name (the other fields - ID, RowGUID and UpdateDate are autogenerated). So my edit form View has only 1 field for the Name (of Product Category). My "Save" action for the edit is below: -
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection){
ProductCategory p = awRepository.GetProductCategory(id);
try
{
//UpdateModel(p);
p.Name = Request.Form["Name"];
awRepository.Save();
return RedirectToAction("Details", new { id = p.ProductCategoryID });
}
catch
{
foreach (var err in p.GetRuleViolations())
{
ModelState.AddModelError(err.PropertyName, err.ErrorMessage);
}
return View(p);
}
}
If I use the code as above, everything works as long as the Name I enter is valid (thus there is no exception). If I introduce an error (which is raised by GetRuleViolations if the Name is blank or for testing purposes is a particular "Test" string) I get a NullReferenceException (Object reference not set to an instance of an object) on this line in the View (Category/Edit.aspx) when the Edit View is redrawn (to show the user the error and allow him to correct)
<%= Html.TextBox("Name") %>
If I update my ProductCategory using UpdateModel(p) instead of using the Request.Form variable, everything works fine; Valid data is saved and invalid data redraws the view showing the error message.
My question is: what is the difference between UpdateModel and manual updating my variable by reading the values from Request.Form collection? The Nerdinner tutorial seems to suggest that both are equivalent. So I am surprised that one works smoothly and the other raises an exception.
Sounds like this:
http://forums.asp.net/p/1396019/3006051.aspx
So, for every error you add with
ModelState.AddModelError() and call
the View again, MVC Framework will try
to find an AttemptedValue for every
error it finds. Because you didn't add
them, MVC will throw an exception.
Normally you don't need to add these
values: AttemptedValues are
automaticaly populated when you use
DefaultBinding (by calling
UpdateModel() or by passing the object
to bind as an Action Method paramter:
public ActionResult
Create(FormCollection Form,
YourObjectType yourObject).
Looks like the following is done automatically by UpdateModel, but not done manually by yourself?
if (Form["Name"].Trim().Length == 0)
{
ModelState.AddModelError("Name", "Name is required");
//You missed off SetModelValue?
ModelState.SetModelValue("Name", Form.ToValueProvider()["Name"]);
}

Categories

Resources