0

I used extension method and wrote a drop-down list, Now I want to get the selected value from view and pass to controller. How can do it?

public static MvcHtmlString DayDropDownCalender(this HtmlHelper helper)
{        
    TagBuilder daydropdown = new TagBuilder("select");

    for (int i = 1; i <= 31; ++i)
    {
        var option = new TagBuilder("option");
        option.SetInnerText(i.ToString());
        option.MergeAttribute("value", i.ToString());
        daydropdown.InnerHtml += option.ToString();
    }

    return MvcHtmlString.Create(daydropdown.ToString(TagRenderMode.Normal));
}

1 Answer 1

1

You should give your <select> element a name attribute:

TagBuilder daydropdown = new TagBuilder("select");
daydropdown.Attributes["name"] = "day";

and then your [HttpPost] controller action could simply take it as argument:

[HttpPost]
public ActionResult Index(string day)
{
    ... the day parameter will contain the selected value
}

or if you want to pass more than a simple scalar value to the controller action you would simply design a view model that will contain all the information needed:

public class MyViewModel
{
    public string Day { get; set; }
    public string Month { get; set; }
    public string Year { get; set; }
    ...
}

that your controller action will take:

[HttpPost]
public ActionResult Index(MyViewModel model)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.