简体   繁体   中英

set value for a textbox in partial view razor mvc

I have following scenario:

My Index page, uses a layout which has a partial View ebbeded in it. the partial view contains a search text box.

For a particular scenario, i need to set the text of the search box with my viewdata[] for index page.

is it somehow poosiblein mvc3, asp.net 2010 to set the value of textbox in partial view from the viewpage?

You could make your partial strongly typed to some view model:

@model SearchViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Keywords)
    @Html.EditorFor(x => x.Keywords)
    <button type="submit">OK</button>
}

and then when inserting the partial you could pass this view model:

@Html.Partial("_Search", new SearchViewModel { Keywords = "some initial value" })

or even better the view model of your main view will already have a property of type SearchViewModel and you will be able to call the partial like this:

@Html.Partial("_Search", Model.Search)

Now obviously in your Index action you no longer need to use any ViewData, but you could directly work with your strongly typed view model:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        Search = new SearchViewModel
        {
            Keywords = "some initial value"
        }
    };
    return View(model);
}

You can always make the partial view strongly typed (even if the model is just a string) and pass the value you need.

public class MyModel
{
    public int ValueForView {get;set;}
    public string TextBoxValue {get;set;}
}

-Index.cshtml

@model MyModel

@{ Html.RenderPartial("PartialView", Model.TextBoxValue); }

-PartialView.cshtml

@model string

@Html.TextBoxFor(m => Model)

As I understand your issue, the partial view is in your layout and you need to get data into it.

In this case layouts are processed last but passing data to it your options are somewhat limited. You can use an ActinFilter or ViewData. ViewData is the easiest, and also the messiest so I don't recommend it.

ActionFilters would work, but you could just process your partial by simply calling in your layout:


 @Html.RenderAction("PartialViewAction", "PartialViewController")

Unless I'm missing something I don't believe the other answers addressed that this is in a layout, hence a different issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM