Show/hide div class based on the variable in the controller - c#

I have a string in the controller which queries Rest API stores the response
string rmID = searchLogic.GetRoomID(rmName.Substring(0, rmName.IndexOf(' '))).Result;
This field is not in the Model class. I need to check if the string rmID is Empty or Null in the Index.cshtml and show/hide a div class
#{
if (String.IsNullOrEmpty(rmID))
{
<div class="row" style="padding-bottom:2rem">
<div class="col-md-9" style="margin-left:auto;margin-right:auto;text-align:center">
<b>
**You have selected not valid room**
</b>
</div>
</div>
}
}
But the above one doesnot work

Use ViewBag to pass the value of rmID from controller to the View.
string rmID = searchLogic.GetRoomID(rmName.Substring(0, rmName.IndexOf(' '))).Result;
ViewBag.Id = rmID;
Then in the view, Use #ViewBag.Id to receive the value and do judgement.
View
#if (!String.IsNullOrEmpty(#ViewBag.Id))
{
<div class="row" style="padding-bottom:2rem">
<div class="col-md-9" style="margin-left:auto;margin-right:auto;text-align:center">
<b>
**You have selected not valid room**
</b>
</div>
</div>
}

Related

ASP.NET Core. Get value from a Select tag without JavaScript

I want to call a specific Action with a parameter that corresponds to the the selected element in a tag.
The Model of the View can be simplified as follows:
public class Model
{
public string SelectedElement {get; set}
public List<SelectListItem> Elements { get; set; }
}
That i'm trying to display in the View:
<h2>Info</h2>
<div class="row">
<div class="form-group row">
<label for="selector-info" class="col-sm-2 col-form-label">Elements</label>
<div class="col-sm-10">
<select id="selector-info" asp-for="#Model.SelectedElement " asp-items="#Model.Elements">
</select>
</div>
</div>
</div>
<div class="row">
<a class="btn btn-primary"
asp-controller="Info"
asp-action="Export"
asp-route-element="#Model.SelectedElement ">
Exportar
</a>
</div>
And the action in the controller:
[Route("export/{element}")]
public async Task<IActionResult> Export(string element)
{
// Do something with the data
return RedirectToAction("Info");
}
Here what I'm trying to do is to call this specific Action that accepts a parameter, and fill it with the selcted element in the tag
But the generated HTML href was incorrect, and debugging I found out that the value Model.SelectedElement was not beeing set correctly.
On the other hand if I wrap this code inside a form and change the link to a button it works. My problem with this is that I'll have multiple buttons (at least 2) that will do different actions but in all cases the selected value of the tag must be passed when the button is clicked.
Is there a way to achieve this? I know I can get the value through JavaScript but I'm trying to find a way to do this directly in ASP without JS.

C# ASP.NET MVC 5 - Type 'System.Web.Mvc.MvcHtmlString' is not enumerable

Here is the context :
This is my first ASP.NET MVC web application.
On the categories list, I click on a category to see all infos about it in a new view.
From this view, I display its name, its description and the number of products in this category.
Below that, I want to display all products in this category.
I gave a try to the Html.Action() method.
But when I want to iterate through the foreach statement, Visual Studio tells me that Type 'System.Web.Mvc.MvcHtmlString' is not enumerable.
Here is my view (details about a category):
#model UlysseCMS.Models.category
#{
ViewBag.Title = "Details about "+ Model.category_name + " category";
var nbProducts = Html.Action("GetNumberOfProductByCategory", "Product", Model.category_id);
var productsList = Html.Action("GetListOfProductsByCategory", "Product", Model.category_id);
}
<div>
<span class="leader">
<span class="mif-chevron-thin-right fg-teal"></span>
<span>#Html.ActionLink("Categories", "Index")</span>
<span class="mif-chevron-thin-right fg-teal"></span>
<span>#Model.category_name</span>
<span class="mif-chevron-right fg-teal"></span>
<span>details</span>
</span>
</div>
<br />
<hr class="bg-teal" />
<br />
<div class="margin30">
<div class="flex-grid">
<div class="row cells7">
<div class="cell colspan3 offset1 sub-header">
Category name :
</div>
<div class="cell colspan4">
#Model.category_name
</div>
</div> <br/>
<div class="row cells7">
<div class="cell colspan3 offset1 sub-header">
Category description :
</div> <br/>
<div class="cell colspan4">
#Model.category_description
</div>
</div> <br/>
<div class="row cells7">
<div class="cell colspan3 offset1 sub-header">
Number of products in this category :
</div>
<div class="cell colspan4">
#nbProducts
</div>
</div>
</div>
</div>
#foreach (var item in productsList)
{
}
Here is my GetListOfProductsByCategory() method from the ProductController :
public IEnumerable<product> GetListOfProductsByCategory(int id)
{
return db.product.Where(x => x.product_category_id == id);
}
I still continue to find a solution with IEnumerable casting or something.
Thanks,
Hellcat.
The result of #Html.Action is a View.
When you have an action inside a controller, this action usually return a view, and that rendered view is result of Html.Action ,for displaying it you need to use an # before html.
You should write your code as below:
public ActionResult GetListOfProductsByCategory(int id)
{
return View(db.product.Where(x => x.product_category_id == id));
}
Then right click on View and from menu select Add View, then create a partial view.
inside partial view you can enumerate your list and create the rendered out put.
Finally wherever you want to show the rendered list, just call:
#Html.Action("GetListOfProductsByCategory",id)
When creating view, you need to select your model and view type as list so on top of your view you would have:
#model IEnumerable<product>
Then you must use you foreach as below:
#foreach (var item in Model)
{
}
Okay I modified my Partial View (GetListOfProductsByCategory) like that :
#model IEnumerable<UlysseCMS.Models.product>
#foreach (var item in Model)
{
<a href="#Url.Action("Details", new { id = item.product_id })">
<div class="tile tile-wide bg-white block-shadow margin30" data-role="tile">
<div class="tile-content slide-up-2">
<div class="slide fg-darkTeal">
<span class="sub-leader" style="padding-left: 5px;">#Html.DisplayFor(modelItem => item.product_name)</span>
</div>
</div>
</div>
</a>
}
And in my Category Details View I display the products like this :
#Html.Action("GetListOfProductsByCategory", "Product", Model.category_id)
It's now okay hanks to Mehrdad Babaki's answer.

MVC 5 Viewmodel binding works but post back is partial filled

I have a parameterless Index for the HttpGet which works. But when I post it the HttpPost version of Index is invoked and the viewmodel object is passed in, but there is only the value of the dropdown in it. The rest is null (products, title)
[HttpPost]
public ActionResult Index(ProductsViewModel pvm)
{
// breakpoint on line 36, shows that pvm.Title is null and Products too.
return View(pvm);
}
My compilable and running example can be downloaded from my OneDrive http://1drv.ms/1zSsMkr
My view:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect"})
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
If I have this view model:
public class ViewModel
{
public string Name {get;set;}
public string SelectedLocation {get;set;}
public IEnumerable<SelectListItem> Locations {get;set;}
}
And your actions look like this:
public ActionResult MyForm()
{
var vm = new ViewModel
{
Locations = context.Locations.ToList() // Some database call
}
return View(vm);
}
[HttpPost]
public ActionResult MyForm(ViewModel vm)
{
vm.Locations // this is null
}
It is null because the model binder can't find a form control that is setting its data.
The <form> must set some data in the view for the model binder to pick it up.
<form>
Name: <input type="text" id="name" />
</form>
This will set the Name property on the view model, because the model bind can see the id of the form control and uses that to know what to bind to.
So in terms of your view, you need to make sure you wrap any content that you want to post back to the server with #using(Html.BeginForm())
Anyway this is my guess.
Well, you seem to be confused as to how [HttpPost] and form tags interact with eachother.
You see, when .NET MVC binds your parameters in your controller actions, it tries to derive that data from the request. For [HttpGet] it does this by looking at the query string.
For [HttpPost] calls, it also looks at the Request.Form. This variable is populated with the values of all input fields that were inside the form you submitted.
Now, this is your view:
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#foreach (var item in Model.Products)
{
#Html.DisplayFor(i => item.Name);
}
</div>
}
}
You only have one select tag (generated by Dropdownlistfor) but no other inputs. That's why .NET MVC cannot infer any other data for your view model.
If you change your view to this:
#model KleinKloteProductOverzicht.Models.ProductsViewModel
#using (Html.BeginForm("Index", "Products"))
{
<h2>#Html.DisplayFor(m => m.Title)</h2>
<input type="submit" value="post dit" /><br/>
<div class="row">
<div class="col-lg-2 col-md-2">
#Html.DropDownListFor(x => x.CurrentSort, EnumHelper.GetSelectList(typeof(SortOptions)), new { #class = "multiselect" })
</div>
</div>
if (Model.Products.Count() > 0)
{
<div class="row">
#for (var i = 0; i < Model.Products.Count; i++)
{
#Html.DisplayFor(model => model.Products[i].Name)
#Html.HiddenFor(model => model.Products[i].ID)
}
</div>
}
}
You'll see I've added a hidden input (<input type="hidden">) for the product id. Note that the product name still will be null.
I would suggest you follow a tutorial on .NET MVC and read up on some of the concepts behind it, because the very fact that you ask this question reveals that you have much to learn.
Best of luck!
P.S. One last tip: #Html.Blablabla writes directly to your view. You usually don't need that ";" at the end, because it will be inside your generated html.
Your property is not associated with a "postable" control, therefore it will not be submitted along with the form data. If your really want to get the value in your Title property, just set it as a hidden input.
#Html.HiddenFor(m => m.Title)
A label will not be posted when submitting a form but an input will. This is exactly what HiddenFor does; it creates a hidden input element which will be picked up by the form submit.

How can I query a view partial and render it in a modal?

I have a view partial in a strongly typed controller. Is it possible to render the would-be contents of that view partial on mouseclick?
Example:
Active View
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div id="modalView"></div>
<script>
$(document).ready(function () {
$('.open-popup-link').magnificPopup({
key: 'my-popup',
type: 'inline',
inline: {
// Define markup. Class names should match key names.
markup: '<div class="white-popup"><div class="mfp-close"></div>awesome</div>'
}
},
{
callbacks: {
open: function(){
}
}
});
$('.open-popup-link').on('mfpOpen', function(e /*, params */) {
var linkText = // how to I grab this? (e.g. 1, 2, 3, or 4)
$.ajax({
// call view partial withlinktext as parameter
//on success
// var inlineContent = viewPartialContent
// On error
// var inlineCOntent = 'Uh oh, something went wrong'
});
});
});
</script>
View Partial
#model *******.Models.Reservation
<div class="container">
<div class="section-heading">
<h2 class="red">Confirm Your Reservation</h2><br />
</div>
<div class="section-content">
<div class="row">
<h3 class="black text-center">Are you sure you want to reserve space <span class="dark-red">#Model.SpaceNumber</span></h3>
<h4 class="black text-center">for <span class="dark-red">#Model.Game.Description</span> on <span class="dark-red">#Model.Game.Date.ToShortDateString()</span>?</h4>
</div>
<div class="row">
<div class="hero-buttons text-center">
No
<form action="/api/Reservations" method="post" id="confirmationForm">
#Html.Hidden("eRaiderUserName", #Model.eRaiderUserName)
#Html.Hidden("SpaceNumber", #Model.SpaceNumber)
<input type="submit" value="Yes" class="btn btn-red btn-lg white">
</form>
</div>
</div>
</div>
</div>
Method for viewpartial in controller
public ActionResult Confirm(int spaceNumber)
{
var reservation = new Reservation { SpaceNumber=spaceNumber, UserName=AppSettings.CurrentUserName, Game=db.Games.FirstOrDefault(g => g.ID == AppSettings.CurrentGameID) };
return View(reservation);
}
Does this make sense, and can I make it work?
You need to do two things:
change your Confirm method, so that it returns PartialView(reservation) instead of View(reservation)
You need to use AJAX, for example jQuery ajax, to get the HTML, and render it in your page
$.ajax({url = 'the url for your Confirm action',
type = 'GET',
dataType='html',
data = params}).done(function(html) {
// use the jQuery and the html to inject it wherever you need in your page
});
NOTE: params is a jQuery object which contains the data you need to pass like spaceNumber in this case, i.e.
var params = { spaceNumber: 'spaceNumberValue' }

How to use textbox and ViewBag value in controller method?

#using (Html.BeginForm("sendcode", "Home", FormMethod.Post))
{
<div class="selected">You Selected:</div>
<div class="sname">#ViewBag.selectsong</div>
<div class="enter" style="width:458px;height:37px; text-align:left;">
<div class="selected">Enter your mobile number</div>
<div class="mobileno">
<div><div class="spann">+91</div><input name="MNumber" type="text" class="mobileinput"/></div></div>`enter code here`
<div class="confirm"><input name="" type="button" class="confirmb"value="Confirm"onclick="location.href='#Url.Action("getdetail", "Home" )'/>
</div>
<div class="applicablee">* charges applicable as per your mobile operators</div>
</div>
}
I want to use textbox value and ViewBag value on my controller method which has been defined below?
public string getdetail(string Mnumber, string sSongName)
{
string ss = Mnumber;
string ss1 = sSongName;
return ss;
}
viewbag is a one way property
if you want to return it value you must define your variable as a property of your model
then pass the model as a parameter to your action
If you want to fill your textbox with ViewBag value try this;
<input type="textbox" id="aa" name="aa" value="#Viewbag.X"/>
If you want to pass that value use hidden method Satpal mentioned about.

Categories