Rectangle 27 254

Your question is hard to understand, but if I'm getting the gist, you simply have some value in your main view that you want to access in a partial being rendered in that view.

If you just render a partial with just the partial name:

@Html.Partial("_SomePartial")

It will actually pass your model as an implicit parameter, the same as if you were to call:

@Html.Partial("_SomePartial", Model)

Now, in order for your partial to actually be able to use this, though, it too needs to have a defined model, for example:

@model Namespace.To.Your.Model

@Html.Action("MemberProfile", "Member", new { id = Model.Id })

Alternatively, if you're dealing with a value that's not on your view's model (it's in the ViewBag or a value generated in the view itself somehow, then you can pass a ViewDataDictionary

@Html.Action("MemberProfile", "Member", new { id = ViewData["id"] })

As with the model, Razor will implicitly pass your partial the view's ViewData by default, so if you had ViewBag.Id in your view, then you can reference the same thing in your partial.

If you make your main model implement an interface, you can have the partial view use that interface as a model. Then you can get a lot of reuse out of it.

@Html.Partial("_SomePartial", new Microsoft.AspNet.Mvc.ViewFeatures.ViewDataDictionary(this.ViewData) { { "id", someInteger } });

asp.net mvc - How can I pass parameters to a partial view in mvc 4 - S...

asp.net-mvc asp.net-mvc-4 razor partial-views
Rectangle 27 50

When using forms authentication and the user is not authenticated or authorized the ASP.NET security pipeline will redirect to the login page and pass as a parameter in the query string the returnUrl equal to the page that redirected to the login page. The login action grabs the value of this parameter and puts it in the ViewBag so it can be passed to the View.

[AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

The View then stores this value in the form as shown by this line of code in the View.

@using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))

The reason it is stored in the View is so that when the user does a Submit after entering their user name and password, the controller action that handles the post back will have access to this value.

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

If the model state is valid and they are authenticated by calling the WebSecurity.Login method then it calls the method RedirectToLocal with the value of returnUrl which came from the View, which originally came form the login action that created the View.

The returnUrl value will be null if the user is not redirected to the login page as is the case when they just click on the login link at the top of the page in the default layout. In this case the user will be redirected to the home page after successful login. The whole purpose of the returnUrl is to automatically send the user back to the page they were trying to access before they were authenticated/authorized.

Well, I have this question - does returnUrl reliable enough to base conditional check on it. What I want is to implement specific logic if the redirect is from the AdminController which in this case is returnUrl = /admin string. Even though I think I start to understand how things work I'm still in doubt if this variable is secure enough or it can easily be changed?

It is not secure and can be easily changed since it is in the query string. Anyone can change this value in their web browser.

this didn't work for me. However you can always do: HttpContext.Request.Params["ReturnUrl"];

asp.net mvc 4 - How am I supposed to use ReturnUrl = ViewBag.ReturnUrl...

asp.net-mvc-4 asp.net-mvc-routing simplemembership
Rectangle 27 3

You can not pass a ViewBag value while redirecting to another action. If you are in the same controller you can use TempData to pass values in a session otherwise you can pass the message as a parameter to RedirectionResult like below:

return RedirectToAction("Index", new {message="Your Message"});

and then get it back like this:

public ActionResult Index(string message)
{
    ViewBag.ViewBag.InsertionResult = message;
    return View();
}

This is a general way how to pass messages but I would recommend something like this:

Use a BaseController where all controllers inherits from this one:

Here you can make a custom logic how to handle global message like error messages, notification messages, info messages etc.

public class GlobalMessage
{
   public string Message { get;set;}
   public AlertType AlertType {get;set;}
}
public enum AlertType
{
   Success, Info, Error, Danger//etc
}

In BaseController you would have something like this:

public abstract class BaseController : Controller
{
    protected GlobalMessage GlobalMessage;
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (GlobalMessage!= null)
            {
                filterContext.Controller.ViewBag.GlobalMessage = GlobalMessage;
            }
            else
            {
                GlobalErrorViewModel globalErrorModelView = TempData["GlobalMessage"] as GlobalMessage;

                if (globalErrorModelView != null)
                {
                    filterContext.Controller.ViewBag.GlobalErrorViewModel = globalErrorModelView;
                }
            }
        }
        base.OnActionExecuted(filterContext);
    }

}

In this moment you just have to register new GlobalMessage in Tempdata like below:

public PeopleController : BaseController
{
    [HttpPost]
    public ActionResult Create(PersonModels person)
    {
        try
        {
            // TODO: Add insert logic here
            //Adding to database and holding the response in the viewbag.
            string strInsertion = ConnectionModels.insertPerson(person);
            TempData["GlobalMessage"] = new GlobalMessage{ AlertType = AlertType.Info, Message = "You have successfully added a new person" }

            return RedirectToAction("Index");
        }
        catch
        {
            return View("Index");
        }
    }
}

Then here is the final step how to show data in the view:

I personally use popup or modal window to do this: For example in bootstrapp you would write something like this:

GlobalMessage globalMessage = ViewBag.GlobalMessage as GlobalMessage;
   @if (globalMessage != null)
    {
        <!-- Modal -->
        <div class="modal fade" id="globalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content panel-@globalMessage .AlertType.ToString().ToLower() remove-border-radius">
                    <div class="modal-header panel-heading">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <p class="h-text-primary">@Html.Raw(globalMessage .Message)</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-@globalMessage .AlertType.ToString().ToLower() remove-border-radius" data-dismiss="modal">Close</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    }

Trigger the modal if there is a message:

@if (globalMessage != null)
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#globalMessage').modal('show');
        });
    </script>
}

This example was to show how you can make a system to show different messages. In short terms whatever you want!

c# - The ViewBag content isn't being visualized - Stack Overflow

c# asp.net model-view-controller
Rectangle 27 3

You can not pass a ViewBag value while redirecting to another action. If you are in the same controller you can use TempData to pass values in a session otherwise you can pass the message as a parameter to RedirectionResult like below:

return RedirectToAction("Index", new {message="Your Message"});

and then get it back like this:

public ActionResult Index(string message)
{
    ViewBag.ViewBag.InsertionResult = message;
    return View();
}

This is a general way how to pass messages but I would recommend something like this:

Use a BaseController where all controllers inherits from this one:

Here you can make a custom logic how to handle global message like error messages, notification messages, info messages etc.

public class GlobalMessage
{
   public string Message { get;set;}
   public AlertType AlertType {get;set;}
}
public enum AlertType
{
   Success, Info, Error, Danger//etc
}

In BaseController you would have something like this:

public abstract class BaseController : Controller
{
    protected GlobalMessage GlobalMessage;
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            if (GlobalMessage!= null)
            {
                filterContext.Controller.ViewBag.GlobalMessage = GlobalMessage;
            }
            else
            {
                GlobalErrorViewModel globalErrorModelView = TempData["GlobalMessage"] as GlobalMessage;

                if (globalErrorModelView != null)
                {
                    filterContext.Controller.ViewBag.GlobalErrorViewModel = globalErrorModelView;
                }
            }
        }
        base.OnActionExecuted(filterContext);
    }

}

In this moment you just have to register new GlobalMessage in Tempdata like below:

public PeopleController : BaseController
{
    [HttpPost]
    public ActionResult Create(PersonModels person)
    {
        try
        {
            // TODO: Add insert logic here
            //Adding to database and holding the response in the viewbag.
            string strInsertion = ConnectionModels.insertPerson(person);
            TempData["GlobalMessage"] = new GlobalMessage{ AlertType = AlertType.Info, Message = "You have successfully added a new person" }

            return RedirectToAction("Index");
        }
        catch
        {
            return View("Index");
        }
    }
}

Then here is the final step how to show data in the view:

I personally use popup or modal window to do this: For example in bootstrapp you would write something like this:

GlobalMessage globalMessage = ViewBag.GlobalMessage as GlobalMessage;
   @if (globalMessage != null)
    {
        <!-- Modal -->
        <div class="modal fade" id="globalMessage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content panel-@globalMessage .AlertType.ToString().ToLower() remove-border-radius">
                    <div class="modal-header panel-heading">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    </div>
                    <div class="modal-body">
                        <p class="h-text-primary">@Html.Raw(globalMessage .Message)</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-@globalMessage .AlertType.ToString().ToLower() remove-border-radius" data-dismiss="modal">Close</button>
                    </div>
                </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
        </div><!-- /.modal -->
    }

Trigger the modal if there is a message:

@if (globalMessage != null)
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('#globalMessage').modal('show');
        });
    </script>
}

This example was to show how you can make a system to show different messages. In short terms whatever you want!

c# - The ViewBag content isn't being visualized - Stack Overflow

c# asp.net model-view-controller
Rectangle 27 1

You can not pass a non-constant value to an attribute, so your solution can not be implemented.

However, you can pass a const value from config file. If you are accepting behaviour like the following: validation of the string will be of single maximum length for a whole lifetime of application and to change it you should reboot an app, take a look at variables in application config.

If you does not accept this behaviour, the one of possible solutions is to store your MaxLength somewhere in database and create your own StringLengthAttribute, which will query DB (or another data source) during valigation in the following way:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class MyValidationAttribute : ValidationAttribute
{
    public MyValidationAttribute()
    {

    }

    public override bool IsValid(object value)
    {
        if (value != null && value.GetType() == typeof(string))
        {
            int maxLength = //query your data source

            return ((string)value).Length <= maxLength;
        }

        return base.IsValid(value);
    }
}

Another possible solution is to perform client-side validation instead of server-side. If you will query your data source from the client-side it will look better, than querying it from attribute, in my opinion.

asp.net mvc - MVC data annotations - dynamic string length - Stack Ove...

asp.net-mvc data-annotations
Rectangle 27 1

You can not pass a non-constant value to an attribute, so your solution can not be implemented.

However, you can pass a const value from config file. If you are accepting behaviour like the following: validation of the string will be of single maximum length for a whole lifetime of application and to change it you should reboot an app, take a look at variables in application config.

If you does not accept this behaviour, the one of possible solutions is to store your MaxLength somewhere in database and create your own StringLengthAttribute, which will query DB (or another data source) during valigation in the following way:

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class MyValidationAttribute : ValidationAttribute
{
    public MyValidationAttribute()
    {

    }

    public override bool IsValid(object value)
    {
        if (value != null && value.GetType() == typeof(string))
        {
            int maxLength = //query your data source

            return ((string)value).Length <= maxLength;
        }

        return base.IsValid(value);
    }
}

Another possible solution is to perform client-side validation instead of server-side. If you will query your data source from the client-side it will look better, than querying it from attribute, in my opinion.

asp.net mvc - MVC data annotations - dynamic string length - Stack Ove...

asp.net-mvc data-annotations
Rectangle 27 85

The @Url.Action() method is proccess on the server-side, so you cannot pass a client-side value to this function as a parameter. You can concat the client-side variables with the server-side url generated by this method, which is a string on the output. Try something like this:

var firstname = "abc";
var username = "abcd";
location.href = '@Url.Action("Display", "Customer")?uname=' + firstname + '&name=' + username;
@Url.Action("Display", "Customer")
server-side
client-side

You are awesome!

first time i have ever seen a solution to this problem with an example.

I ended up adding an onclick event to a <a> element which appended to the href attribute which was set using Url.Action

But what if without that parameter the path is different?

c# - Passing dynamic javascript values using Url.action() - Stack Over...

c# javascript asp.net asp.net-mvc url.action
Rectangle 27 6

You can have 3 separate form tags, one for each button. Just make sure you have an input field inside the form for the data you want to pass. For example if your action method is accepting the EmployeeId with a a parameter called EmployeeId, you should have in input hidden field with the same inside the form.

@model IEnumerable<Employee>
<table>
@foreach(var item in Model)
{
   <tr>
       <td>@item.EmployeeName</td>
       <td>@item.EmployeeGender</td>
       <td>@item.EmployeeCity</td>
       <td>@item.EmployeeDateOfBirth</td>
       <td>
         @using(Html.BeginForm("Details","YourControllerName"))
         {
           <input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
           <input type="submit" value="Details" />
         }
         @using(Html.BeginForm("Edit","YourControllerName"))
         {
           <input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
           <input type="submit" value="Edit" />
         }
         @using(Html.BeginForm("Delete","YourControllerName"))
         {
           <input type="hidden" name="EmployeeId" value="@item.EmployeeId" />
           <input type="submit" value="Delete" />
         }
       </td>
   </tr>

}

Also remember, nested forms are invalid HTML. So make sure you do not have those.

This one works for me. One said that using multiple submits inside single form is bad idea? Is It valid If so can any body give explanation?

asp.net mvc - How to pass value from submit button to mvc dynamically?...

asp.net-mvc asp.net-mvc-4
Rectangle 27 58

1st Approach (via Request or FormCollection):

You can read it from Request using Request.Form , your dropdown name is ddlVendor so pass ddlVendor key in the formCollection to get its value that is posted by form:

string strDDLValue = Request.Form["ddlVendor"].ToString();
FormCollection

If you want with Model binding then add a property in Model:

and in View:

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")

and in Action:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{           
   string SelectedValue = MV.SelectedVendor;
   return View(MV);
}

If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectVendor {get;set;}
    public string SelectedvendorText { get; set; }
}
<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
   $("#SelectedvendorText").val($(this).text());
 });
});
</script>

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)

@Raghubar, Just set the value of property SelectVender in the controller to match the value of one of the options

MV.Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName",VM.SelectedVendor);

c# - How to get DropDownList SelectedValue in Controller in MVC - Stac...

c# asp.net asp.net-mvc asp.net-mvc-4
Rectangle 27 6

Get the value of your textboxes using val() and store them in a variable. Pass those values through $.post. In using the $.Post Submit button you can actually remove the form.

<script>

    username = $("#username").val(); 
    password = $("#password").val();

    $("#post-btn").click(function(){        
        $.post("process.php", { username:username, password:password } ,function(data){
            alert(data);
        });
    });
</script>
serialize

@SeanVieira I don't know how to use that. What's the purpose of it? I've been learning that but just can't understand :) Please tell me

serialize takes a form (or a set of inputs) and turns all of the input, select, and textarea tags into a string suitable for sending as the body of an HTTP POST request (or as the query string of a GET request). For example, serializing a form with the single field, <input name="firstName" value="Sean"> becomes "firstName=Sean".

@SeanVieira ok thanks and then you just need to post or get the firstName? :)

Yes - then you can directly use that string in $.ajax or any of its cousins ($.post, $.get), as this answer does

javascript - How to use jquery $.post() method to submit form values -...

javascript php jquery post
Rectangle 27 2

The short answer to your question is NO. Doing a user level validation from a web service can slow down your whole system and more importantly it does not add any value. Instead of doing that, what you need to do is make sure that the Web Service is secured and cannot be accessed by unauthorised parties. To achieve that, you can use Certifications, WSS, SSL, firewalls etc.

Let's assume this webservice is used in a school to publish exam results. So obviously students should not be able to access it. So you have to control that at your application level, not at the web service level. You can of cause allow students to send a message to the WS and then get a response from the WS saying "You are not authorised to do this". But it will consume your resources unnecessarily. It will also slow down your system.

The 2nd scenario that you have mentioned is valid. It's good practice to have a middle layer, so that you can cater to multiple versions of the external web service, without changing your core application. If the external application is not very reliable, you can also handle reliability issues gracefully using this middle layer. For an example, suppose the external service is used for ledger posting. Which means your application will post any given transaction only once. What do you do if it fails? You can have a retry mechanism in your middle layer. So likewise a middle layer can actually add more value to your system if it's designed carefully.

Could you explain what you have in mind for certifications? I am looking into certificates, but not sure how this would work later for app implementations in iOS or Android. Client certificates shouldn't be static, as it is considered to be insecure? Thanks!

c# - Securing a 'pass through' web service - Stack Overflow

c# asp.net web-services security
Rectangle 27 1

The action link isn't going to trigger a http post nor will it pass in the values of your form fields, just a http get and not passing through any form data - ideally you'd use an input submit button to post the data. What is certain is that it is good practise that any request that causes creating/updating of data should be done via a http post.

Submit button would just be like.

<input type="submit" value="Send" />

You then have several ways of accessing the form data firstly you could use a FormCollection to access the data

Secondly you could use the method parameters and rely on model binding, but you must make sure field names match the parameter name so

<%: Html.TextBox("txtEmail", "", new { style = "width:100%" })%>
[HttpPost]
public ActionResult SendEmail(string txtEmail)
{
    ...
}

If this form isn't being posted to the same action thats return the view then you'd also need to change your begin form tag, ideal you should use 'using' with it as well. So you'd get:

<% using (Html.BeginForm("SendEmail", "<controller-name>"))
   { %>
.... form fields in here ...
<input type="submit" value="Send" />
<% } %>

If the button isn't suitable for your design you could use something like:

<input type="image" src="<%: Url.Content("~/Content/images/myimage.gif") %>" value="Send" />

This would have the same effect. To trigger a post from an a tag though you'd need to look at using javascript, I can't remember the exact syntax but off hand I think if you used jquery you'd be looking at something like: (form a single form page only)

<a href="#" click="$('form').submit(); return false;">Send</a>

But then you create a dependency on javascript where as really you should try have your site degrade gracefully so it can be used by visitors with javascript disabled. There are perhaps more advanced way of achieving this whilst meeting design requirements but that can get heavily into client side code which is probably outside of what you want for your sample.

I should have mention in the ways of accessing the form data you could create a class to act as a strongly typed container for your form data - such view models are the best way in the long run. And the model binding is in mvc is very powerful.

Thanks for the help Mark, much appreciated. Your explanation was really good and helped me understand a more about how this works.

Passing Parameters from textboxes in a view to a controller in ASP.Net...

asp.net-mvc-2 parameter-passing actionlink
Rectangle 27 4

ViewBag is like ViewData. In order to have information between pages you should store that info in session. You can do that in 2 ways:

Use a session variable like:

this.Session["SessionVariable"] = value;

Or use the this.TempData object:

this.TempData["SessionVariable"] = value;

The difference between this two is that the TempData object will be deleted from the session when it is read.

TempData is just a wrapper of the session.

asp.net mvc 3 - How to pass value from one action to another action ha...

asp.net-mvc-3 model-view-controller viewbag
Rectangle 27 3

Attributes are essentially metadata added to a type. They can only use const values, instead of instance variables. In your case you are tying to pass in your instance variables of genisisRepository, etc. This will fail to compile as they are not compile time constants.

You should look into Dependency Injection for Action Filters to achieve this, typically using an IoC container.

Also, if your ActionFilter is performing a post ActionResult action, such as OnActionExecuted, you could probably get away with storing something in the route data:

public ActionResult Index()
{
  ControllerContext.RouteData.DataTokens.Add("name", "value");
  return View();
}

+1 for providing further guidance...dependancy injection is the ideal solution in this case; service location is another (simpler) option to consider as well.

Well... I'm not sure that this is possible then. md.memberGUID is bound to the session and cannot be a const because the site will need access to update login data.

Why not read from the session in the ActionFilter?

Adding things into route data that aren't in the URL is a pretty horrible way to store data. That leads to hard to find bugs. -- Dependency Injection doesn't really help solve this issue. Anything technique that provides the repositories to the ActionFilter will work. Now of course DI is better to help stop the service location issues but its not THE solution, just one way of enabling the solution. Good article on how to achieve this: lostechies.com/blogs/jimmy_bogard/archive/2010/05/03/

You don't need IoC to inject it, but IoC might make it easier. You could declare the filter in your filter config, inject its dependencies into the constructor, and then register the filter.

c# - How to pass parameters to a custom ActionFilter in ASP.NET MVC 2?...

c# asp.net asp.net-mvc action-filter
Rectangle 27 24

There's no model yet in the OnActionExecuting event. The model is returned by the controller action. So you have a model inside the OnActionExecuted event. That's where you can change values. For example if we assume that your controller action returned a ViewResult and passed it some model here's how you could retrieve this model and modify some property:

If you want to modify the value of some property of the view model that's passed as action argument then I would recommend doing this in a custom model binder. But it is also possible to achieve that in the OnActionExecuting event:

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var model = filterContext.ActionParameters["model"] as MyViewModel;
        if (model == null)
        {
            // The action didn't have an argument called "model" or this argument
            // wasn't of the expected type => no need to continue any further
            return;
        }

        // modify some property value
        model.Foo = "bar";
    }
}

Hi, do you maybe know how can I get the action's passed parametrs like the ActionDescriptor.ActionParameters in OnActionExecuting event?

filterContext.ActionParameters["parameterName"]

ok, but I'm in the ActionExecutedContext case.

You have no access to action parameters in the OnActionExecuted method. That's because there's no action anymore when this method executes. The action has finished. From the filterContext.ActionDescriptor property you could get the list and the type of each argument but not the value. One possibility is to store the values that you need to access in the HttpContext inside the OnActionExecuting method and then retrieve them in the OnActionExecuted method from the HttpContext.

asp.net mvc - Change the model in OnActionExecuting event - Stack Over...

asp.net-mvc asp.net-mvc-3 model-view-controller action-filter
Rectangle 27 1

You can use a ViewModel to avoid converting the string value from Request.Form. Below is how your ViewModel class should look like

public class MyViewModel
{
    public MyViewModel()
    {
        this.DropdownItems = new List<SelectListItem>();
    }

    public int SelectedSiteId { get; set; }
    public List<SelectListItem> DropdownItems { get; set; }
}

Change the get action method in your controller as below

public ActionResult Index()
{
    List<Site> sites = db.Sites.ToList();

    MyViewModel model = new MyViewModel();

    foreach(var site in sites)
    {
        model.DropdownItems.Add(new SelectListItem() { Text = site.Name, Value = site.ID.ToString() });
    }

    return View(model);
}

Add @model MyViewModel at the first line in your view code and use Html.DropDownListFor method to generate the dropdownlist

@model MyViewModel

@using (Html.BeginForm("SetSite", "Home"))
{
    @Html.Label("SelectedSiteId", "Site:");
    @Html.DropDownListFor(m => m.SelectedSiteId, Model.DropdownItems, new { @class = "selectpicker" })
    <div style="width:100%;height:25px"></div>
    <button class="btn btn-default" style="width:100%">Go</button>
}

The post action method in your controller should look like below. model.SelectedSiteId will be the selected value of the dropdownlist and the type is int so you won't have to do any conversion such as Convert.ToInt32(Request.Form['Sites']).

[HttpPost]
public ActionResult SetSite(MyViewModel model)
{
    Session["Site"] = model.SelectedSiteId;
    return RedirectToAction("Home");
}

c# - How to pass the ID of an object from a form to an action in ASP.N...

c# asp.net asp.net-mvc razor
Rectangle 27 2

I second @Vivien's response, but I would recommend to use the overload that takes the selected value (See MSDN:), which you can then set. To then allow passing in the default, I would also recommend using a static method, and allowing the month to be passed in:

public static SelectList PossibleMonths(string defaultValue)
{
        return new SelectList(List<SelectListItem>()
        {
            new SelectListItem() { Text = "1 - Jan", Value = "1" },
            new SelectListItem() { Text = "2 - Feb", Value = "2" },
            new SelectListItem() { Text = "3 - Mar", Value = "3" },
            new SelectListItem() { Text = "4 - Apr", Value = "4" },
            new SelectListItem() { Text = "5 - May", Value = "5" },
            new SelectListItem() { Text = "6 - Jun", Value = "6" },
            new SelectListItem() { Text = "7 - Jul", Value = "7" },
            new SelectListItem() { Text = "8 - Aug", Value = "8" },
            new SelectListItem() { Text = "9 - Sep", Value = "9" },
            new SelectListItem() { Text = "10 - Oct", Value = "10" },
            new SelectListItem() { Text = "11 - Nov", Value = "11" },
            new SelectListItem() { Text = "12 - Dec", Value = "12" },
        }, "Value", "Text", defaultValue);
}
@Html.DropDownList(Model.ModelPropertyPrefixName + "CreditDetails.ExpirationMonth", Helpers.PossibleMonths(Model.CreditDetails.ExpirationMonth),
                new { id = Model.ModelPropertyPrefix + "CreditDetails_ExpirationMonth", @class = "form-control", style = "width:70px;" })

That assumes the CreditDetails object is always not null, otherwise null checking is a must.

EDIT: I was incorrect, apparently Html.DropDownList doesn't support SelectList, so I reverted back to the original approach with a twist for setting the selected value (note same drop down code above for this to work).

public static IEnumerable<SelectListItem> PossibleMonths(string defaultValue)
{
        if (defaultValue == null)
           defaultValue = "";

        return new List<SelectListItem>()
        {
            new SelectListItem() { Text = "1 - Jan", Value = "1", Selected = (defaultValue == "1") },
            new SelectListItem() { Text = "2 - Feb", Value = "2", Selected = (defaultValue == "2") },
            new SelectListItem() { Text = "3 - Mar", Value = "3", Selected = (defaultValue == "3") },
            new SelectListItem() { Text = "4 - Apr", Value = "4", Selected = (defaultValue == "4") },
            new SelectListItem() { Text = "5 - May", Value = "5", Selected = (defaultValue == "5") },
            new SelectListItem() { Text = "6 - Jun", Value = "6", Selected = (defaultValue == "6") },
            new SelectListItem() { Text = "7 - Jul", Value = "7", Selected = (defaultValue == "7") },
            new SelectListItem() { Text = "8 - Aug", Value = "8", Selected = (defaultValue == "8") },
            new SelectListItem() { Text = "9 - Sep", Value = "9", Selected = (defaultValue == "9") },
            new SelectListItem() { Text = "10 - Oct", Value = "10", Selected = (defaultValue == "10") },
            new SelectListItem() { Text = "11 - Nov", Value = "11", Selected = (defaultValue == "11") },
            new SelectListItem() { Text = "12 - Dec", Value = "12", Selected = (defaultValue == "12") },
        };
}

Can you kindly guide me how my cshtml file gonna change as per your helper code.

As far as I have studied I need to pass one more argument (telling dropdown to take a default value and display it) in the @Html.DropDownList right?

Also, when I say default value I mean to say the logged is user's model data. I mean the form needs to be auto filled by the model data. Not a hardcoded default value. Just saying. I am sure you would have figured that out.

Well no, selected value is not a property on Html.DropDownList. You either need to set the Selected attribute on the SelectListItem class, or use SelectList and specify the selected value parameter (4th param in the method I have above). The view passes the value stored in the model as the default (yep, are that we are not hard-coding a "2" value).

My bad, my original method was wrong and Vivien was right, but turns out Html.DropDownList doesn't support SelectList at all, so I just modified your original approach to set the selected property for the correct entry. You may be able to use the SelectList class and use the Items property to get the list of SelectListItem collection anyway, so either approach should work.

c# - How to set the value of dropdown coming from model in ASP.NET MVC...

c# asp.net asp.net-mvc razor asp.net-mvc-5
Rectangle 27 1

Hmm. You can specify a VaryByCustom attribute on the OutputCache item. The value of this is passed as a parameter to the GetVaryByCustomString method that you can implement in global.asax. The value returned by this method is used as an index into the cached items - if you return the number of comments on the page, for instance, each time a comment is added a new page will be cached.

The caveat to this is that this does not actually clear the cache. If a blog entry gets heavy comment usage, your cache could explode in size with this method.

Alternatively, you could implement the non-changeable bits of the page (the navigation, ads, the actual blog entry) as user controls and implement partial page caching on each of those user controls.

c# - Clearing Page Cache in ASP.NET - Stack Overflow

c# asp.net outputcache
Rectangle 27 1

this is a sample of html page send a variable to aspx page and in cs file of aspx page you can use the coming variables from html page normally in cs code of aspx

protected void Page_Load(object sender, EventArgs e)
        {
            string s = Request.Form.Get("param1");
        }

in HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>

    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>

    <script src="jquery.mobile-1.1.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        myFunction = function() {
            var txtValue = document.getElementById("mytxt" ).value;
            try {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx",
                    data:"param1=" + txtValue ,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    dataType: "html",
                    success: function(msg) {
                    },
                    error: function(xhr, status, error) {
                        alert('Error');
                    }
                });
            }
            catch(e)
            {
                alert(e);
            }

        };


    </script>


</head>
<body>
    <table >
        <tr>
            <td id="blah">
                <input id="mytxt" type="text" />
            </td>
        </tr>
        <tr>
            <td>
                <input type="button" value="Redirect" onclick="myFunction()" />
            </td>
        </tr>
    </table>
</body>
</html>

yes, your second answer is much better. By the way, may I know which book that teach you the code that you provide?

it's not a book i get that code from search experience :) but any way u can try this book advanced javascript "Chuck Easttom" most people said it's amazing but i didn't read it :)

javascript - How to pass value from HTML to a ASPX files in Visual Stu...

javascript asp.net html variables