Can I use ASP.NET MVC Partial in my case? - asp.net-mvc

I new to ASP.NET MVC so this question maybe simple for you but please give me more detail :)
In my app there is a Menu, all of this Menu Item store in Database, the Menu showing every pages. I think what I need is Partial but I not sure how!
BTW I can always use ajax, so which way is better?
Thanks for yout time!

You may not need this to be a partial view, you can generate it in run time using regular .net code if you have a proper helper function. Anyways, for your question you can do these in a couple of ways.
Create a partial view and load it using the partial tag
#Html.Partial("_LogOnPartial")
or you can write a Html helper function
public static string GetMenus(this HtmlHelper html)
{
//Generate your menu in HTML format
}
and render it using the html renderer
#Html.Raw(Html.GetMenus())
For ajax, you can also write some function which does the same work of GetMenu and call it using an Ajax get.
$.ajax({
url: '/Controller/YourGetMenu',
type: 'GET',
dataType: 'json',
cache: false,
async: false,
data: { ParameterName: itemvalue },
success: function (data) {
//Do the menu rendering work
},
error: function (ex) {
alert('Error.');
}
});
I would go for the second option.

Related

Navigating to different views in Single Page Application

I'm developing Single page web application for which I will be using the MVC and knockout. In the _Layout.cshtml, I will have the menu bar using which user can view different views. When I click on the items in menu, I will be calling controller method and being a single page application, I will have to return partial view. However, I'm confused how I can load returned partial view exactly in my view area. If I use Ajax.BeginForm, I can specify the UpdateTargetID in which I need to update my partial view but as with menu item click, it will just be server method call. So I wonder how I can update the partial view inside view area?
Do you think writing following javascript function for each menu items is what I need to do?
$('#menuitemId').click( function() {
$.ajax({
type: 'POST',
url: '#Url.Content("~/ControllerName/ActionName")',
data: objectToPass,
success: function (data) {
$('#divid').innerHTML = data; // data is partial view returned from controller
}
});
}
Also, can someone point me/share working demo/good documents of Single page web application with MVC and knockout?
That looks fine to me.
You could also make it simpler like this:
$('#menuitemId').click( function() {
$('#divid').load('#Url.Content("~/ControllerName/ActionName")' + menuItemId);
});

How to do MVC form with very simple lookup?

We have a very simple MVC form with a dropdownlist which gets the user's selected city.
We have a list of cities and we know the average temperature (say) for each city.
Almost as a decoration (it's not a core function) for the form it would be nice to show the temperature for the selected city as the user changes it. Something like this:
This has to happen client side, I guess. Or is it AJAX?
At the moment our form is mostly out-of-the-box MVC4 EF auto built with scaffolding.
We populate the dropdownlist like so:
In the Controller:
ViewData("Cities") = GetCitySelectList()
and in the View:
#Html.DropDownListFor(Function(model) model.City, TryCast(ViewData("Cities"), SelectList))
... so pretty simple stuff.
There are plenty of tutorials for doing cascading dropdowns which are probably overkill for what we're trying to do here. Also if you google "javascript lookup mvc form" or similar a lot of the results tie you to using a framework (knockout? barebone?) which, again, I'm not familiar with and I don't know if I need for such a simple task.
In fact we're so geared to keeping it simple, and our city list is so short, it's almost worth doing it as a giant if then else in javascript (but, I know, yuk).
What's the simplest way to do this?
You can do it as follows:
Make an Ajax call on change on dropdown and then place the result in the corresponding div.
Html for result:
Temperature:<div id="temp"></div>
Ajax call :
$("#dropdownId").change(function () {
$.ajax({
type: "GET",
url: "Home/GetTemperature", // your url
contentType: "application/json; charset=utf-8",
data : {City : " + $(this).val() +"}
dataType: "json",
success: function (result) {
$("#temp").html(result); // place result in div
},
error: function () {
alert("Error.");
}
});
});
Your Action (C#):
[HttpGet]
public JsonResult GetTemperature(string City)
{
int temp = 30; // Get temp from your db..
return Json(temp,JsonRequestBehavior.AllowGet);
}
Your Action (VB):
<HttpGet>
Public Function GetTemperature(City As String) As JsonResult
Dim temp As integer = 30
Return Json(temp, JsonRequestBehavior.AllowGet)
End Function
You should use AJAX call to the server for the temperature. That's probably the "cleanest" way to achieve what you would like to have on your form.
Option 1: Using jQuery and make ajax call to fetch a temprature for the cityId passed and set the html of the temprature div or span container
Option 2: Eager Load on page as Javascript object
You could have eager load the cities and temprature into the JSON object and store it.
Here is the controller action code using JSON.Net for json serialization
public ActionResult myAction()
{
MyViewModel model=new MyViewModel();
List<City> cities=new List<City>();//fill the city id, temp
MyViewModel.CityJSON=JsonConvert.SerializeObject(List<City>);
return View(model)
}
View
#model MyViewModel
// other controls
#Html.HiddenFor(m=>m.CityJSON, new{#id='hdn-city-json'})
JavaScript
var cityList=JSON.parse($('#hdn-city-json')); // returns array of city obj
//do your stuff
If you are trying to avoid unneccesary requests to server, yes, you could eager load the whole collection. You can keep the data in a hidden <ul/> tag that you build on your View. Then, you can use jQuery to fire when the dropdown selection changes. But instead of making an AJAX call, you can lookup the temperature in the list instead and set the content of the target div to the return value of the lookup function.

MVC partial render

if renderpartial in MVC is not like Update panel in ASP.net. than how does it works, and what about the efficiency. I heard that update panel was so inefficient in use. But how does MVC handles postbacks, I need to undestand this before I can dive into MVC
Any suggestions
thank you
ASP.MVC Partial views are just reusable HTML fragments that can be populated by View Models. They don't have any special built in functionality like update panels do.
In general terms, with ASP.MVC you control post backs. In fact, you have to code it all yourself in HTML and JavaScript.
I suggest you start here.
Assuming that you want to update part of your page, the method I use is as follows:
Link a JavaScript function to the event you want to use to update the 'panel'
Make a jQuery AJAX call to an action in your controller
from the controller return a call to the partial view
this will cause the resulting HTML from the partial view to be returned as HTML to your AJAX call
use jQuery to add the HTML to an existing empty div
The AJAX call looks something like
$.ajax({
url: yourControllerAction URL,
data: { CodeTypeID: codeTypeID }, // optional data
type: "POST",
success: function (returnedHtml) {
$("#myDiv").html(htmreturnedHtmll);
}
});
The rest is standard MVC
Hope that helps

I need some clarification on GET and POST concerning JQuery AJAX and MVC 3

I am wondering if it is an all-or-nothing situation. What I would like to do, Load (GET) my page by normal MVC 3. Controller takes Model and passes it to View. View and Razor render it. However, when I post back, I'd like it to postback the selected info through AJAX. Is this possible? Or do I have do GET and POST with AJAX?
You can certainly POST using AJAX after GETting using other means.
Here's a random question on SO that does just this:
Ajax post in MVC 3 with multiple-form View
The GET and POST actions do not have to be related at all.
Try something like the below.
Controller Code:
[HttpGet]
public ActionResult WhateverActionName()
{
YourViewModel yvm = new YourViewModel();
//Initalize viewmodel here
Return view(yvm);
}
[HttpPost]
public ActionResult WhateverActionName(YourViewModel yvm)
{
if (ModelState.IsValid) {
RedirectToAction("OtherAction", "OtherController")
}
return View(yvm);
}
Ajax:
$.ajax({
url: myurl
// processData: false, // you may need this option depending on service setup
success: function(){
location.href = "TARGET LOCATION";
},
type: "POST"
});
For target location: You're going to need to feed the ajax a variable containing whatever URL the following generates
#URL.Action("Action", "Controller")
http://knockoutmvc.com offers an nice way of integrating server side code with client side and it looks like it might help you easily achieve what you want.

Does ASP.NET MVC provide any way to implement UpdateProgress WebForms control analog?

Does ASP.NET MVC provide any way to implement UpdateProgress WebForms control analog? Can anyone explain me how to achieve such client-side functionality with MVC?
Using a little jQuery and AJAX makes it pretty easy (or complex, if you want to do something hard) to do this. This little snippet updates a DIV from a method that renders a partial view to HTML. It first replaces the current contents with a loading message, then updates the DIV with the response from the server by overwriting the loading message when the data is returned. You can do other things like showing an animated GIF or get really complex and set up an interval timer to periodically check the status of a long running activity and do a progress meter. Obviously, the latter is much more complex.
$('#myButton').click( function() {
$('#myDiv').html('Please wait while the data is loaded.');
$.ajax({
url: '<%= Url.Action( "action" ) %>',
data: $('form').serialize(),
type: 'post',
dataType: 'html',
success: function(data,status) {
$('#myDiv').html( data );
}
});
});

Resources