Passing parameters from Controller to View in C# [duplicate] - c#

MVC newbie question:
I'm picking up a URL of the form go/{mainnav}/{subnav}, which I've successfully routed to the GoController class, method:
public ActionResult Index(string mainnav, string subnav) {
return View();
}
So far, so good. But now I want the view to return different HTML, depending on the values of mainnav or subnav. Specifically, inside a javascript block, I want to include the line:
myobj.mainnav = [value of mainnav parameter];
and, only if subnav is not null or empty:
myobj.subnav = [value of subnav parameter];
How do you pass those parameters to an aspx page that doesn't have a codebehind?

You use a ViewModel class to transfer the data:
public class IndexViewModel
{
public string MainNav { get; set; }
public string SubNav { get; set; }
public IndexViewModel(string mainnav, string subnav)
{
this.MainNav = mainnav;
this.SubNav = subnav;
}
}
Your action method then comes out
public ActionResult Index(string mainnav, string subnav)
{
return View(new IndexViewModel(mainnav, subnav));
}
This means your view has to be strongly typed:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<YourNameSpace.IndexViewModel>" %>
In your view, you output the data like so:
myobj.mainnav = <%: Model.MainNav %>;
An alternative solution if you use MVC3, would be to use the dynamic ViewBag:
public ActionResult Index(string mainnav, string subnav)
{
ViewBag.MainNav = mainnav;
ViewBag.SubNav = subnav;
return View();
}
which would be accessed in the page as so:
myobj.mainnav = <%: ViewBag.MainNav %>;
However, I would recommend that you read up on unobtrusive javascript and see if you can improve your design to avoid this specific problem.

If you are using MVC3 I would suggest passing the values into the ViewBag.
ViewBag.MainNav = "xxxx";
ViewBag.SubNav = null;
then on your view page, where you define the JavaScript and add the value.
if you dont have MVC 3 if you use ViewData["MainNav"]), to store your value has the same effect.

Did you try accessing parameters from Request in your view?
i.e.
Request.Params["mainnav"]
or
Request.Params["subnav"]
Works in MVC

i'm using following approach:
ViewModel.class:
public class TitleBodyModel
{
public string Title { get; set; }
public string Body { get; set; }
public TitleBodyModel() { Title = Body = ""; }
public TitleBodyModel(string t, string b) { this.Title = t; this.Body = b; }
}
In the main View:
#Html.Partial("_TitleBody" , new XXX.Models.TitleBodyModel("title", "body" ))
Then in a partial view:
#model XXX.Models.TitleBodyModel
<div class="bl_item">
<div class="bl_title">#Model.Title</div>
<div class="bl_body">#Model.Body</div>
</div>

If i understand this can be a solution:
public ActionResult Index(string mainnav, string subnav)
{
return View(mainnav | subnav);
}
In the Html View you can use View
and after
<%=Model %>

Related

Specify different body class for each page in partial view header

I'm newby to MVC and I want to have different body class for each view.
My header is a partial view and #RenderSection does not work for it.
_Layout.cshtml:
#{
Html.RenderAction("GetHeader", "Main");
}
#RenderBody()
#{
Html.RenderAction("GetFooter", "Main");
}
_HeaderLayout.cshtml:
//...
<body class=" here must be specified class different for each view">
//...
MainController:
public class MainController : Controller
{
public ActionResult GetHeader()
{
return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
}
public ActionResult GetFooter()
{
return PartialView("~/Views/Shared/_FooterLayout.cshtml");
}
}
Any idea please?
I would do it in two ways:
Create a base ViewModel class for all the view models used in your app and add a property for the BodyClass, then implement it in the Partial View.
Add a property in the ViewBag dictionary before returning the partial view.
Examples:
1. Base class
public class BaseViewModel
{
public string BodyClass {get; set;}
}
Usage:
Base Class:
in partial view:
#model BaseViewModel
///...
<body class="#Model.BodyClass">
in controller:
public ActionResult GetHeader()
{
var vm = new BaseViewModel { BodyClass= "test-class" };
return PartialView("~/Views/Shared/_HeaderLayout.cshtml", vm);
}
In ViewBag:
public ActionResult GetHeader()
{
ViewBag[SomeConstantStringValue] = "test-class";
return PartialView("~/Views/Shared/_HeaderLayout.cshtml");
}
in partial view:
<body class="#ViewBag[SomeConstantStringValue]">
Remember that you always have to specify that ViewBag value, otherwise you'll get an error.
Mihail Stancescu answer is probably best, but if you don't want a view model for each controller method, you could make use of a helper function instead. Either way though, your're going to probably have to make your own method that decides which class to return (see BodyClassForTabAndMethod() below).
Create a Helper class (if you don't have a suitable one already):
public static class Helper
{
public static string BodyClassForTabAndMethod()
{
string[] selectedTabAndMethod = GetSelectedTabAndMethod();
string bodyClass = "";
// Change the below switch statements based upon the controller/method name.
switch (selectedTabAndMethod[0])
{
case "home":
switch (selectedTabAndMethod[1])
{
case "index":
return "IndexClass";
case "about":
return "AboutClass";
case "contact":
return "ContactClass";
}
break;
case "account":
switch (selectedTabAndMethod[1])
{
case "login":
return "LoginClass";
case "verifycode":
return "VerifyCodeClass";
}
break;
}
return bodyClass;
}
public static string[] GetSelectedTabAndMethod()
{
string[] selectedTabAndMethod = new string[2]; // Create array and set default values.
selectedTabAndMethod[0] = "home";
selectedTabAndMethod[1] = "index";
if (HttpContext.Current.Request.Url.LocalPath.Length > 1)
{
// Get the selected tab and method (without the query string).
string tabAndMethod = HttpContext.Current.Request.Url.LocalPath.ToLower();
// Remove the leading/trailing "/" if found.
tabAndMethod = ((tabAndMethod.Substring(0, 1) == "/") ? tabAndMethod.Substring(1) : tabAndMethod);
tabAndMethod = ((Right(tabAndMethod, 1) == "/") ? tabAndMethod.Substring(0, tabAndMethod.Length - 1) : tabAndMethod);
// Convert into an array.
if (tabAndMethod.Count(s => s == '/') == 1)
{
string[] split = tabAndMethod.Split('/');
selectedTabAndMethod[0] = split[0];
selectedTabAndMethod[1] = split[1];
}
}
return selectedTabAndMethod;
}
public static string Right(string value, int length)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
return ((value.Length <= length) ? value : value.Substring(value.Length - length));
}
}
And then in your view:
<body class="#Helper.BodyClassForTabAndMethod()">
I reached to a solution for my own question, very simply:
In Global.asax: //or any other class which loading at start
public static class WrrcGlobalVariables
{
//any other global variables...
public static string BodyClass { get; set; }
}
In any Controller and before returning view/partial view:
public ActionResult Index()
{
//some codes...
WrrcGlobalVariables.BodyClass = "HomePage";
return View();
}
and in _HeaderLayout.cshtml:
<body class="#WrrcGlobalVariables.BodyClass">
Both the approaches given by Mihail Stancescu are correct, however there is one more way to have a default value for it and custom value only when required. Also you should use RenderPartial as well for your case instead of RenderAction if all you're doing is rendering the partial without any extra logic which requires a child controller.
In _Layout.cshtml
#Html.Partial("_HeaderLayout")
#RenderBody()
#Html.Partial("_FooterLayout")
In _HeaderLayout.cshtml
<body class="#ViewBag[SomeConstantStringValue]">
In _ViewStart.cshtml
#{
ViewBag[SomeConstantStringValue] = ViewBag[SomeConstantStringValue] ?? "default-class";
}
Then anywhere in any view or controller set this ViewBag value, this way you'll ensure a guaranteed default value to prevent null reference exceptions

C# Razor Syntax - html.displayfor displaying as text, not html

My models:
public class htmlDump {
public string html { get; set; }
}
public string getSquares() {
var sq = (from s in n.squares
where s.active == true
orderby s.date_created descending
select s.html).First();
return sq;
}
My controller:
public ActionResult index() {
intranetGS.htmlDump sq = new intranetGS.htmlDump {
html = g.getSquares()
};
return View(sq);
}
My View:
#Html.DisplayFor(model => model.html)
All I want is for the html being passed to the view to be rendered as html and not as text. Surely there's something different I can use in the view (instead of .DisplayFor) that will work. Any suggestions?
Thanks very much!
#Html.Raw(Model.html)
NOTE: if this data can be input by the user - make sure it's sanitized.

Passing an array from Controller to View using Model

I'm trying to pass an array from my controller to my view using my Model. My method does not work for some reason. I've posted it below.
Controller:
public ActionResult Confirmation()
{
string[] Array = new string[2] {"Pending", "07/07/2013"};
ConfirmationModel Con = new ConfirmationModel
{
Status = Array[0],
AppDate = Array[1],
};
return View();
}
Model:
public class ConfirmationModel
{
public string Status { get; set; }
public string AppDate { get; set; }
}
View:
#model site.ConfirmationModel
#{
ViewBag.Title = "Confirmation";
}
#Html.DisplayFor(Mode => Model.Status)
#Html.DisplayFor(Mode => Model.AppDate)
You aren't passing your model to your view. Change the line below:
return View();
To this;
return View(Con);
You haven't actually included the model in the result. Do this:
return View(Con);
You should return populated model to your view. In your case:
return view(con)
Then use con in your view.
You're not passing any model to the view to be rendered.
The View() method has an overload to receive an object model to render in the view.
Try this: return View(Con);

getJson doesn't call JsonResult for models rendered with PartialView

So I have this application in ASP MVC 3.
My database has two tables: Comenzi and DetaliiComenzi with one-to-many relationship (and Link-to-Sql) - in my application I want my users to buy some products by making a oder(stored in table comenzi) and for that order a list of products he wants to buy (will be stored in DetaliiComenzi with Order.id as foreign key).
Basically, after I create a new entry for Comenzi, I want to be able to make a list of products for that order (something like a shop chart but the user will choose his products in a view, adding how many products as he likes).
I have used Steve Sanderson’s method of editing (and creating) a variable length list.
-- Here is the model for which I create the list.
When I'm choosing a single product to oder I must first select the Group (Grupa) which he belongs to from a dropdownlist (using ListaGrupe) and then from a second dropdownlist (ListaProduse) a product from that particular group of products I selected in the first dropdownlist.
public class Comd
{
public string Grupa { get; set; }
public string Produs { get; set; }
public string Cantitate { get; set; }
public string Pret { get; set;}
public string TVA { get; set; }
public string Total { get; set; }
public List<SelectListItem> ListaGrupe
{
get;
set;
}
public List<SelectListItem> ListaProduse
{
get;
set;
}
}
--The Controller:
public ActionResult ComandaDetaliu(string id)
{
Comd model = new Comd();
IProduseRepository _prod = new ProduseRepository();
model.ListaGrupe = _listecomanda.GetGrupe();
string first = model.ListaGrupe[0].Value;
model.ListaProduse = _listecomanda.GetProduse(first);
string pret = _prod.GetByDenumire(model.ListaProduse[0].Text).pret.ToString();
model.Pret = pret;
double fr = 0.24;
model.TVA = fr.ToString();
var data = new[] { model };
return View(data);
}
-- The View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<InMVC3.Models.Comd>>" %>
<%# Import Namespace="InMVC3.Helpers"%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Comanda numarul: <%: RouteData.Values["id"].ToString()%></h2>
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<% foreach (var item in Model)
Html.RenderPartial("ProduseEditor", item);
%>
</div>
<%= Html.ActionLink("Adauga alt produs", "Add", null, new { id = "addItem" }) %>
<input type="submit" value="Finished" />
<% } %>
-- The Partial View "Produse Editor"
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<InMVC3.Models.Comd>" %>
<%# Import Namespace="InMVC3.Helpers" %>
<div class="editorRow">
<script type="text/javascript">
$(document).ready(function () {
$("#Grupa").change(function () {
var url = '<%= Url.Content("~/") %>' + "Comenzi/ForProduse";
var ddlsource = "#Grupa";
var ddltarget = "#Produs";
$.getJSON(url, { id: $(ddlsource).val() }, function (data) {
$(ddltarget).empty();
$.each(data, function (index, optionData) {
$(ddltarget).append("<option value='" + optionData.Value + "'>" + optionData.Text + "</option>");
});
});
});
});
</script>
<% using(Html.BeginCollectionItem("comds")) { %>
Grupa: <%= Html.DropDownListFor(x => x.Grupa, Model.ListaGrupe) %>
Produsul: <%= Html.DropDownListFor(x => x.Produs, Model.ListaProduse) %>
Cantitate: <%=Html.TextBoxFor(x=>x.Cantitate) %>
Pret: <%=Html.DisplayFor(x => x.Pret, new { size = 4})%>
TVA: <%= Html.DisplayFor(x=>x.TVA) %>
Total: <%=Html.DisplayFor(x=>x.Total) %>
Sterge
<% } %>
-- And the JsonResult method
public JsonResult ForProduse(string id)
{
throw new NotSupportedException();
JsonResult result = new JsonResult();
var produsele = _listecomanda.GetProduse(id);
result.Data = produsele;
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return result;
}
All I need to know is how to make the call to the JsonResult action because this is what doesn't works so that when I change the selected value in the first dropdownlist to dynamically change the second too.
Of course, I also need to change the other properties too but that after I get how to make getJson to work.
If you need more details please tell me.
UPDATE 1:
--The Helper
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
string key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null) {
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (string previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
UPDATE
I now have another issue. When I Post that list to the actiont, I get the following error at the foreach statement inside the controller action: Object reference not set to an instance of an object.
-- The Controller Action
[HttpPost]
public ActionResult ComandaDetaliu(IEnumerable<Comd> comenzi)
{
if (ModelState.IsValid)
{
foreach (var item in comenzi)
{
detalii_comenzi det = new detalii_comenzi();
det.id_comanda = Convert.ToInt32(RouteData.Values["id"].ToString());
det.id_produs = Convert.ToInt32(item.Produs);
det.cantitate_comandata = Convert.ToDecimal(item.Cantitate);
det.cantitate_livrata = 0;
det.pret =Convert.ToDecimal(item.Pret);
det.tvap = Convert.ToDecimal(item.TVA);
}
return RedirectToAction("Index");
}
return View(comenzi);
}
Your problem is the duplicate IDs - Every row has a dropdown with ID "Grupa" so your jquery selector will match the dropdowns in every row.
You need to add a prefix to the controls - there are several ways to achieve that - a search for "mvc3 field prefix" brings up several other questions:
How to define form field prefix in ASP.NET MVC
ASP.MVC 3 Razor Add Model Prefix in the Html.PartialView extension
ASP.NET MVC partial views: input name prefixes
Most of those are focused on mapping when the form is posted, but the same issue applies with your javascript.
You could just update the ids in your script to something like "##(ViewBag.Prefix)Grupa", but a better approach would be to use classes instead of ids in your selector and make the script reusable - something like:
ddlSource = this;
ddlDest = this.Parent().find(".produs");

Get posted selected item from DropDownList in ASP MVC

Controller
public ActionResult Create()
{
return View(new PageViewModel());
}
[HttpPost]
public ActionResult Create(Page page)
{
try
{
repPage.Add(page);
repPage.Save();
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
PageViewModel
public class PageViewModel
{
public Page Page { get; set; }
public List<Template> Templates { get; set; }
private TemplateRepository repTemplates = new TemplateRepository();
public PageViewModel()
{
Page = new Page();
Templates = repTemplates.GetAllTemplates().ToList();
}
}
Parts of my View
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Website.Models.PageViewModel>" %>
<%= Html.TextBoxFor(model => model.Page.Name, new { #style = "width:300px;" })%>
<%= Html.DropDownListFor(model => model.Page.Template, new SelectList(Model.Templates, "ID", "Name"), new { #style = "width:306px;" })%>
Template:
ID
Name
Page:
ID
Name
TemplateID
My dropdownlist is populated correctly in the view, no problems there. My problem is that I dont get the selected value from the dropdownlist.
In my controller I i put a breakpoint in Edit and see that the Name textbox is populated with the value I type into it. But the selected from the dropdownlist is set to null.
alt text http://www.mgmweb.no/images/debug.jpg
Am I missing something, I thought it should set the correct Template value into the Page object. What am I doing wrong?
Try something like this maybe?
The key in the collection is the name of the dropdownlist control...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
string selectedvalue = collection["Template"];
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
The only thing that you get back from the web page is the id of the selected template. The default model binder doesn't know how to take this id and retrieve the correct template object from your repository. To do this you would need to implement a custom model binder that is able to retrieve the values from the database, construct a Template object, and assign it to the Page. Or... you could do this manually in the action given that, according to your comments elsewhere, you know how to get the template's id from the posted values.
Ok, I did like this:
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
Page page = new Page();
page.Name = collection["Page.Name"];
page.TemplateID = int.Parse(collection["Page.Template"]);
page.Created = DateTime.Now;
repPage.Add(page);
repPage.Save();
return RedirectToAction("Edit");
}
catch
{
return View(new PageViewModel());
}
}
And it works good, I just wanted to know if there is a better way to to this without manually getting the values from the collection.
But I guess it is not possible without making your own model binder as tvanfosson said.
Thank you everyone.
for model binding, use in the ActionResult:
partial ActionResult(FormCollection form)
{
Page page = new Page();
UpdateModel(page);
return view(page);
}
your class:
public class Page
{
public string Name {get; set;}
public int Template {get; set;}
public DateTime Created {get; set;}
public Page()
{
this.Created = DateTime.Now;
}
}
attribute names in your class should be equal to the name of the fields of view

Categories

Resources