I am new to MVC.
I have a string that I built from a controller called parsedCustomerNames. In web forms I can make the placeholder visible from the codebehind and then populate a control with the string.
How would I be able to do this in MVC.
I believe parsedCustomerNames is a coma separated list of customers (As opposed to a collection). You can do it like this in ASP.NET MVC:
Suppose, following is your controller:
public class HomeController : Conroller{
public ActionResult Index(){
ViewData["ParsedCustomerNames"] = parsedCustomerNames; //Get the string here.
return View();
}
}
And then inside your view, do the following:
<div class="customerName">
<%: ViewData["ParsedCustomerNames"] as string %>
</div>
Here you don't need placeholder as such.
Place this logic of showing this string inside a "Div". If you have anything in string, div will appear otherwise it will be as good as invisible.
Another thing to focus is that Asp.Net MVC is not event driven as normal Asp.Net is. You need to think in terms of Get and Post. Everything you do in Asp.Net MVC will be a result of user action which will be Get/Post. Every action will provide some data (M of MVC) to your view and you will have to redraw your page (v of MVC). If you have any data on particular "div" then it will appear automatically otherwise not.
Related
I'm a php head and getting to grips with ASP.NET MVC 5.
In php, after submitting checkbox fields, in order to post back the form with the checkboxes you checked initially set to true, you have to run a if isset on em.
However reading up on model binding in mvc, it seems that this is done automatically for you, i.e checkboxes are returned after form submit checked, if originally selected, using either the HTML.CheckBox or HTML.CheckBoxFor helpers.
Is this the case, or am I expecting too much of MVC?
No, ASP.NET MVC doesn't remember checkbox values after they're submitted. Being an HTTP application as soon as ASP.NET MVC has rendered the HTML it ends the request and forgets everything about what it's just done. Then upon submitting a form ASP.NET MVC processes the incoming HTTP request and maps it to your model via its model binding (more on how it does this in a moment).
Having come from a PHP background myself this is one of those questions I always had when starting with ASP.NET MVC.
With ASP.NET MVC you have to remember that you're working within the context of a complete framework, and in order to ensure you're as productive as possible ASP.NET MVC will take care of a lot of the mundane work for you - ASP.NET MVC's model binding is a perfect example of this.
When submitting a form, the ASP.NET MVC framework will parse all incoming post data and attempt to automatically map it to the values you're providing it via your controller action.
So where as in PHP you'd normally do something along the lines of:
if(isset($_POST['checkboxValue'])) {
$checkboxVal = $_POST['checkboxValue'];
}
ASP.NET MVC will automaltically bind the incoming post data to your action parameter like so:
[HttpPost]
public ActionResult Submit(bool checkboxValue){
}
It does this by checking the parameter name (checkboxValue) matches that of the post data array key, and that the type also matches up. For instance, if you were to change the above checkboxValue from a boolean to a string and change the name, then ASP.NET MVC's model binding will be unable to match the property to the post data and will not automatically set the value for you.
It's also worth noting that ASP.NET MVC's model binding doesn't know how you created the checkbox.
The HTML.CheckBox and HTML.CheckBoxFor html helpers are purely a means to make it easier for you to create the HTML. If you were to manually write the HTML yourself then the model binder will still successfully bind the submitted data.
Edit:
As #DrinkBird has quite rightly pointed out, you're also able to access all of your form's post data by using the FormCollection instance like so:
[HttpPost]
public ActionResult Submit(FormCollection postData){
}
This collection represents all of the data posted to the Submit action.
Yes, model-binding should allow you to retrieve the value of a checkbox on submission.
if your model looks like:
public class myModel
{
public bool myBool {get; set;}
}
and in your HTML, you've used the helper
#Html.CheckBoxFor(m => m.myBool)
Then in your post action to handle the submission:
[HttpPost]
public ActionResult MyAction(myModel model)
{
var whatsThis = model.myBool;
}
...whatsThis will be true if the checkbox was checked, false if not.
Part of why this works is that when you use #html.CheckBoxFor, it also places a hidden form field that will pass false if the box is unchecked, to aid with model binding -- if it didn't, per HTTP there would be no varibalbe 'myBool' submitted in the post-vars collection.
If you return this model back into the form (say, if it didn't validate), then the form will re-present the checkbox in whatever state it was in on submission:
[HttpPost]
public ActionResult MyAction(myModel model)
{
if(!ModelState.IsValid)
{
return View(model);
}
else
{
//do success
}
}
In Asp.net , there is user control, which is an ascx page, and we can have hidden fields:
public partial class classA:System.Web.Mvc.ViewUserControl<Models.classB>
{
//hidden field
public string url
{
get{ ...... }
}
}
But now i am using razor in asp.net mvc3 ,which is cshtml file. Do we have anything corresponding to that? How can i use hidden field now?
MVC views do no have fields like a Web Forms user control.
MVC views (partial views, too) get their data by passing an instance of a Viewmodel class to them. You can indicate the type of the viewmodel class with the #model directive (usually the first line in a view):
#model MyViewmodelClass
<span>#Model.MyClassProperty</span>
The viewmodel class itself could contain private fields like any class.
If you need variables to be used within the view itself, you can simply declare them within a razor code block and use them wwithin the view:
#{
var privatevar = "value";
}
<span>#privatevar</span>
However, as a best practice, the view's responsibility in ASP.NET MVC should be limited to the display of the data and therefore not contain code unrelated to that.
While working with razor it is essential to have basic HTML knowledge as you need to write some html and there is no and Drag and Drop to add controls on the page.
MVC have introduced Partial Views which can be said a alternate/replacement to User Control.
You can create a PartialView by selecting Checkbox stating "Create Partial View" in View Creation Dialog. Secondly In MVC it is not difficult to create partial view mannual as well.
As you are using Razor, just set Layout = null; at the top of your view and it will be treated as partial view. Secondly you can easily make any field as hidden using display property under Style attribute.
Happy Coding :)
I'm trying to migrate an existing ASP.NET Webforms 3.5 application into an ASP.NET MVC 3 application. That means, I attempt to convert existing .aspx pages with webcontrols and codebehind recpectively with controller logic and razor views.
At the moment I'm focusing on the master page (to get an analogue layout.cshtml for all other razor views).
For example I've replaced controls like asp:Menu, asp:LoginView with partial views and #Html.Action to invoke the controller action, run some code that has been in the codebehind of that masterpage before and return that partial view.
But now I'm getting lost with many web controls of the masterpage that have been set in/visible, depending on the code behind. For example there are two asp:panels in the master page that have been switched in/visible depending on the visited page.
The problem is that in razor views I don't have web controls and in controllers I cannot set attributes/properties (like private int counter;).
Thus I don't know how to carry on...
I hope you have got some ideas or experience with this situation.
Please ask if any information is missing.
You can either set properties of the Model or ViewData in the Controller and then use these in the Razor view with #if
e.g.
On the controller:
public ActionResult Index()
{
ViewBag.Foo = IsThisFoo();
View();
}
In the View:
#if (ViewBag.Foo) {
<p>This is foo</p>
}
else
{
<p>This is bar</p>
}
nb: best practice would be to do it as part of a strongly typed Model for the view
I have a viewpage and a partialview on that. For default request-when page is called- CultureInfo is set in base class of viewPage. I have created this custom base class which initialize the culture depending on a cookie and does some other stuff as well. There is a search button on the view page which updates a partial view on the page with Ajax call (jquery Ajax call). There is separate action for this partial view update call which returns partial view. The problem is partial view do not have any base class and when resources are displayed on partial view they are displayed for default culture and not the current culture. What would be best approach to set cultureInfo when partial view is called from jQuery Ajax call?
I have this mvc application as part (area) of bigger existing application so I can not touch session_start.
I'm not sure why you need to pass the culture around, can't you get it directly from your PartialView using a helper method?
#YourApp.CultureHelper.GetCurrentCulture()
which is just calling
public static string GetCurrentCulture()
{
return Thread.CurrentThread.CurrentCulture.Name;
}
If you are doing any work with internationalization and ASP.NET MVC I highly recommend reading through these two excellent posts by Nadeem Afana
ASP.NET MVC 3 Internationalization
ASP.NET MVC 3 Internationalization - Part 2 (NerdDinner)
Very well written and explains everything you need to know about internationalization.
You can send the culture info to your partial view as model with string array.
I guess you have handled the ajax call so I am just gonna show you the way of passing the value. The below one is your controller :
public ActionResult Index() {
return PartialViewResult("samplePartial", new string[] { "en" });
}
And this is your partial view :
#model string[]
#if(Model[0] == "en") {
#:Culture is "en"
} else {
#Culture is different than "en"
}
Also this can be also rendered inside your view as indicated below :
#Html.Partial("samplePartial", new string[] { "en" })
A function returns only one view.
what if I want to return multiple views in a function?
For example, I have this code:
Function Index() As ActionResult
Dim _news As DataTable = News.newsSelect()
Dim _announcement As DataTable = Announcement.SelectAnnouncement()
Return View()
End Function
I want to return _news and _announcement to be used in the aspx page. How would I do this?
Are you trying to show both sets at the same time? News and Announcements?
If so then why not implement either a PartialView or two PartialViews?
Then in your main view you can render them and pass the collection to the PartialViews?
There are heaps of samples on this and the one I recommend is in NerdDinner if you haven't already seen it.
I hope this helps. If you want sample code then let me know.
One simple way is just to have those two datasets sent in a ViewData element, which you can access in a field.
example:
ViewData["Elements"] = new SelectList(aElements, "Guid", "Name");
is consumed as:
<%= Html.DropDownList("Elements","Pick an element")%>
Also, I think that if you read between the lines of this blog post here you will find an elegant way of achieving what you want ;) but its a bit more involved..(only because you mentioned Views instead of just variables..
Quote:
We need to create our own implementation of IViewFactory. This
is responsible for locating and
creating an instance of an IView
(which both ViewPage and
ViewUserControl implement).
To “inject” (all you DI fans excuse me borrowing the term without
using a DI framework) our new View
Factory into every Controller we are
going to create our own
IControllerFactory implementation.
We need to configure the framework to use our new Controller
Factory.
Finally we can create two Views – an AJAX version and a pure
HTML version.
Building on that should be all you need
Good luck!
Ric
Assuming what you are trying to do is use both of those DataTables to populate some View, then my recommendation would be to create a wrapper object and then a strongly typed view based on this object.
The wrapper object would contain properties for all of the data elements that you need in order to render your view properly. In your case, it is 2 DataTable objects. I do not really know VB, so all my examples will be in C#. Here is an example of the data wrapper class...
public class IndexViewData
{
public DataTable News { get; set; }
public DataTable Announcement { get; set; }
}
You then might update the Index action in your controller as follows:
public ActionResult Index()
{
var viewData = new IndexViewData();
viewData.News = News.newsSelect();
viewData.Announcement = Announcement.SelectAnouncement();
return View(viewData);
}
Finally, you would need to create/update your view to be strongly typed. This is done by having your page inherit from the generic System.Web.Mvc.ViewPage<T> class. Just substitute the view data wrapper created earlier for T. To do this, you would set the inherits attribute of the <%# Page %> element. In your case, if we assume your root namespace is called "Foo", you might have the following page declaration in your Index.aspx view (added extra line breaks for readability):
<%# Page Title=""
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<Foo.Models.MyModelType.IndexViewData>"
%>
Once you have a strongly typed view for your view data wrapper, you can access the wrapper object in your view using the Model property. Here is an example of something you could do in your Index.aspx view
<%-- Output some random data (bad example, for demonstration only) --%>
<%= Model.News[0]["title"] %><br/>
<%= Model.Anouncement[0]["body"] %>
In reality you're probably going to do something like iterate over each row of the data table. Regardless, once you create the strongly typed view, your model object, which was passed to the view in the Index method of the controller, is available in the Model property within the view.
You can find detailed tutorials at the ASP.NET MVC site