Set Selected Value of @Html.DropDownList to Querystring value or not

I have a typical Create Action that was generated by scaffolding in MVC 4. Nothing fancy. Normally I get to this page by the following URL /RecipeLines/Create and when I create that specific record I have a dropdown list I have altered to receive recipeID if sent:

    <div class="editor-label">
        @Html.LabelFor(model => model.RecipeID, "Recipe")
    </div>
    <div class="editor-field">
        @Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID, string.Empty)
        @Html.ValidationMessageFor(model => model.RecipeID)
    </div>

What I would like to do is link to the Create page by passing a recipeID, that would look something like this:

/RecipeLines/Create/2

I have edited the @Html.DropDownList to either accept a parameter and HOPEFULLY select the proper RecipeID or if it is linked to without the query string

/RecipeLines/Create

then it would not have a selected value.

Here is my Create Action as is.

    // GET: /RecipeLines/Create

    public ActionResult Create(int? recipeID)
    {
        ViewBag.MeasurementID = new SelectList(db.Measurements, "MeasurementID", "MeasurementEn");
        ViewBag.RecipeID = new SelectList(db.Recipes, "RecipeID", "RecipeNameEn", recipeID);
        ViewBag.IngredientID = new SelectList(db.Ingredients, "IngredientID", "IngredientNameEn");
                return View();
    }

My 2 @Html.ActionLink(s) looks like this:

    //Coming from the Recipe Page        
    @Html.ActionLink("+", "Create", "RecipeLines", new { recipeID = recipe.RecipeID }, null);

    //Coming from the RecipeLines/Index page
    @Html.ActionLink("Create New", "Create")

THIS PROBLEM HAS BEEN SOLVED AND THE ABOVE CODE NOW WORKS

Answers


Try below code:

Create Action

public ActionResult Create(int? recipeId)
{
    ViewBag.RecipeID = new SelectList(db.Recipes, "RecipeID", "RecipeNameEn",recipeId);

     //
    return View();
 }

View

  @Html.DropDownList("RecipeID", (SelectList)ViewBag.RecipeID,string.Empty)

ActionLink

@Html.ActionLink("+", "Create", "RecipeLines", new { recipeId= recipe.RecipeID }, null);

@Html.ActionLink("Create New", "Create")

Need Your Help

ksoap2 in Android: noclassdeffounderror on SoapObject

android eclipse ksoap2

I've added ksoap2-android-assembly-2.5.5-jar-with-dependencies to my build path in eclipse and given internet permissions in the manifest. The error is on: 'SoapObject request = new

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.