A Local Or Parameter Named 'ContactForm' Cannot Be Declared In This Scope Because

- 1 answer

I have created a partial view containing a quick contact form. The contact form should be rendered from the _Layout, without passing a model, like so


Within the _QuickContact view i thought of declaring a variable like so

@{ContactForm ContactForm = new ContactForm();}

so i can i use it as

    @Html.TextBoxFor(ContactForm => ContactForm.Email)
    @Html.ValidationMessageFor(ContactFormm => ContactForm.Email)

since i would not like to pass a model at it. (This approach if i am not mistaken, would require tuples or a wrapper containing multiple models).

Unfortunately i get the error

A local or parameter named 'ContactForm' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter

Is there any work around for this?



You model needs a @model ContactForm declaration, and then you can use @Html.TextBoxFor(m => m.Email) etc.

However because you calling this using @Html.Partial(), you need to pass a model (which can be a default instance) to the partial, otherwise the model in the main view will be passed and an exception will be thrown.

@Html.Partial("_QuickContact", new ContactForm())

The alternative would be to use a Html.Action() to call a server method that returns your partial, for example

public PartialViewResult Contact
    return PartialView("_QuickContact"); // or return PartialView("_QuickContact", new ContactForm());

and in the layout

@Html.Action("Contact") // or @{ Html.RenderAction("Contact"); }