In asp.net web forms we have user controls as reusable components for pages. These user controls can be passed values externally through public properties e.g. on a web form we can drop this user control to display a text which came from db (like content managed system) by setting key as public property to this user control and it will pull the value. ( this key, value can be stored in application cache as list or dictionary to avoid DB round trips).
I want to implement same idea in asp.net mvc, but new to it. Any expert suggestion to implement same idea will be very helpful? Thanks
The concept of a user control is a PartialView; there are two ways to use a partial view. The first is to define a partial in the view itself:
#Html.Partial("NameOfViewInControllerFolder", ModelForPartialview)
The second way is have an action method that returns a partial view:
public ActionResult X()
{
return PartialView("NameOfView");
}
And from your view use:
#Html.Action("X", "ControllerName")
And that will call the action method, and insert the results. To ensure that action is only called within the a view, you can use the [ChildActionOnly] attribute.
If an action method, you can use JQuery to request it via AJAX, and load the results into a view:
$.ajax({
type: "GET|POST",
url: "#Url.Action("X", "ControllerName")",
success: function(d) { /* d is HTML */ });
Related
I have an asp.net user control which is plugged into both asp.net and MVC pages
When the control is on an asp.net page the client validation in it works fine but when the control is on an MVC page the following call in the js validation fails;
Page_ClientValidate('ValidationGroup');
with the error in Chrome: Object [object global] has no method 'Page_ClientValidate'
How can I get my client side validation to work on my mvc pages when the hyperlink button is clicked?
I need whatever the solution is to work across both MVC and ASP.Net as our site is a combination of the two
Try something like this,
$('#Form').submit(function () {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
if (Page_IsValid == true) {
alert('the form is valid');
}
} else {
if ($(this).valid()) {
alert('the form is valid');
}
}
});
What Kind of validations are you trying to do?
first option:
MVC gives you great tool for validations:
Have you heard about "Data Annotations" tool?
as you configure your model fields you can use the common validation annotation called "required" for example:
Model:
[Required ("ID Field is Required")]
public int ID {get; set;}
View:
#html.texboxfor(m=>m.ID)
#validatefor((m=>m.ID)
and on the view you'll see a red message next the the input field you're trying to validate.
you can change the default messages design and location using CSS.
There is a good Tutorial for that matter at:
http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-6
there is more data annotation validations, it depends on what kind of validations are you trying to do..
Second option:
you can use validate.js for input validations - it gives you the ability to validate almost any kinds of inputs - from numbers and strings to tables, and you can custom you own validation rules...
Default Option:
Build your Own Validation Method using native js for example:
if( $(.myClass).length<0 )
{
alert( "Please Insert Value" );
return false;
}
EDIT:
you can create :
View:
#using("actionMethod","controller")
{
<!--Content contains "names" of tags-->
<input type="submit"/>
}
OR
Controller:
When post back occurred , check the names and return to the same View, if the names are not satisfy.
end EDIT
If you have more questions, please ask.
Hope I Helped, Good luck.
Is there anyway to use an MVC Razor validation method on an ascx web forms user control that is being embedded in an MVC View using RenderPartial?
The problem I now have is that my ascx user control has a custom validation control on it (just the standard web forms custom validator) and when this control is used on an MVC View (by using Render Partial) the view errors with the following error;
Control 'ctl00_ProductListView_ctrl5_ctl00_ctl00_valValueMultiple' of type 'CustomValidator' must be placed inside a form tag with runat=server.
This is because the MVC view doesn't have a form on it obviously but I can't simply add one.
I cant'simply change this from an ascx web forms user control because it is dynamically added to both MVC and Web Forms pages (we have a mixed site of MVC and Web Forms - this is beyond my control) throughout our website.
My page contains several web user controls. Those controls contains other child controls, and those contains more child controls and so on. From my page, I want to be able to access those controls, like I do with other public classes: uc1.uc1_child1.uc1_child1_child1.Update();
(I do know about the FindControl method, and thats what Im currently using. It's however not type safe, and I need to lookup the names of the controls all the time to be on safe side. Much more time consuming than intellisense)
If you create a public property on your usercontrol for each of the usercontrols it contains, that should work.
eg
public SpecificUserControlType ContainedUserControl
{
get
{
return this.uc1_child;
}
}
Im showing a table of data using a paginated list, with a search box and submit button above this. I wish to be able to search this table of data then re-Post the view and update with the newly searched for data on the click of the submit button. How would I do this in MVC? Would I have to start looking at AJAX or JQuery or can it be done using the built in GET and POST techniques?
Sorry if the question doesn't make a whole load of sense, I'm new here and to MVC :D
The basic pattern is the same whether it's AJAX or not. You would have 2 actions for your view, a GET and a POST, your search form should be a simple ViewModel with the fields you'd search/sort on that also includes your pagination.
[HttpGet]
public ActionResult DataTable(int? page){
var data = myRepository.GetData(page);
return View(data);
}
[HttpPost]
public ActionResult DataTable(int? page, SearchModel search){
var data = myRepository.GetSearchedData(page, search);
return View(data);
}
If you were doing it via AJAX the difference is that you'd have the data display in a PartialView, your DataTable View would render this partial within a named div, the HttpPost method would return a PartialView and you'd replace the named div's contents with this result (JQuery's $.load() method would be the easiest way to do this).
What is the difference between the controller result named ViewResult and PartialViewResult? More importantly, when is the PartialViewResult used?
PartialViewResult is used to render a partialview (fx. just a user control). This is pretty nifty for AJAX stuff, i.e.
<script type="text/javascript">
$.get(
"/MyController/MyAction",
null,
function (data) { $("#target").html(data) }
);
</script>
and action
public ActionResult MyAction()
{
return PartialView("SomeView");
}
where SomeView is a MVC User Control, e.g.:
<div>
<%= DateTime.Now.ToString() %>
</div>
http://msmvps.com/blogs/luisabreu/archive/2008/09/16/the-mvc-platform-action-result-views.aspx
In practice, you’ll use the
PartialViewResult for outputing a
small part of a view. That’s why you
don’t have the master page options
when dealing with them. On the other
hand, you’ll use the ViewResult for
getting a “complete” view. As you
might expect, the Controller class
exposes several methods that will let
you reduce the ammount of typing
needed for instanting these types of
action results.
Generally speaking, ViewResult is for rendering a page with optional master, and PartialViewResult is used for user controls (likely responding to an AJAX request).
none of the existing answers actually answer the question "What is the difference".
The differences are as follows:
1) the locations where the view engine will attempt to find the view:
for ViewResult, it's in ViewLocationFormats and MasterLocationFormats
for PartialViewResult, it's in PartialViewLocationFormats
2) ViewResult has the additional property MasterName
that is all.
There are several cases where you would want to break down your view into several small components. One use case that I am working with right now, is I have a multi-lingual site that I would like to reload content using AJAX principles.
Normally what I would do in the case of a non-multi lingual site is to create another ActionResult to return the ViewModel that is changing with the new parameters. I like to use a custom ActionResult that I have called JsonpResult. The problem resides in the fact that I have labels not in my database but in Resource files. So what I would need to do is to somehow hydrate my Resource file data into the ViewModel.
Once the data comes down the pipe, my AJAX callback handles the wiring up of the ViewModel response back to the HTML page using Javascript (I use jQuery).
This definitely works, however it becomes a question of maintainability. I now need to not only maintain my original ASP.NET view, but I also need to maintain a set of scripts that handle AJAXian behavior. If you need to have your site SEO, then you really need to make sure that both the Server Side and Client Side behavior are both working the same.
This is where Partial Views come into play for me. What I do is "pull out" the logical data sections where the bulk of the reload occurs. The nice thing about PartialView is that you can pass your ViewData and Model along to the PartialView. If your PartialView is strongly typed against your ViewModel you can get Intellisense to help with the wiring of the PartialView.
Now all I need to do with my AJAX call is to write the response back to a single DIV rather than handling data points individually. What it does mean is that there would be more content coming down the pipe. However, the trade off is easier to read and maintain code.
The one of the main differences is PartialViewResult doesn't use _ViewStart.cshtml. The code from _ViewStart.cshtml file executes at the start of rendering before any code in the view.
I am trying to find out how to use usercontrols in asp.net mvc. I know how to add a usercontrol to a view and how to pass data to it. What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?
For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?
I'm not sure if this makes sense or not. Is there a better or recommended way to handle an "island" of data that you want to display on several pages?
I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.
There are multiple ways to do it.
The basic approach is
Populate the data for the view in the BaseController (OnActionExecuting event)
Writing a custom action filter
Writing an Application Controller (the eg. is in the below links).
An example of OnActionExecuting will be
[HandleError]
public class BaseController : Controller
{
CourseService cs = new CourseService();
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
List<Tag> tags = cs.GetTags();
ViewData["Tags"] = tags;
}
}
You can use the "tags" view data on any view. This is just an example of usercontrol being rendered as side content.
<div id="sidebar_b">
<asp:ContentPlaceHolder ID="ContentReferenceB" runat="server" >
<% Html.RenderPartial("Tags"); %>
</asp:ContentPlaceHolder>
</div>
I found the following URL to be useful.
http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx
http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx
http://www.aaronlerch.com/blog/2008/01/26/displaying-foo-on-every-page-of-an-aspnet-mvc-application/
http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/
In the MVC Futures, available on codeplex , contains the RenderAction HtmlHelper extensions. This will allow you to create a controller for the ueser control and this controller will populate the ViewData used by the user control without having to resort to a base controller as was suggested.
In the View you would do
<% Html.RenderAction("Index", "UserControlController") %>
or one of the other overloads.
This will create an instance of the controller, execute the method and render the user control view into the main view. The main view controller does not need to know anything about the user control or its model/data.
Refactor the code that obtains the view data for this user control into it's own method, maybe even it's own model (class). Call this method from each controller that needs to populate the control and pass the results in the ViewData with a well-known key. You might even want to pass the type of the current controller to your method in case it needs to know what data to retrieve based on the base model for the controller.
ViewData["RecentPosts"] = RecentPosts.GetRecentPosts( this.GetType() );
In your control, retrieve the data using the well-known key.
How to Handle "Side Content" in ASP.NET MVC