質問

I am beginner and I think my question is very obvious but I am stuck in it!

In MVC and trying to pass a custom Model (class) which is not my view's main Model to my controller. My Razor code is as follow:

@helper  CreatForm()
    {
        MyViewModel myModel = new MyViewModel();
        using (Html.BeginUmbracoForm("Post", "ShowPost", FormMethod.Post, new { @class = "formCM" }))
    {
        myModel.PostNode = Node.GetCurrent();
        <div class="row">
            @Html.TextBoxFor(x =>  myModel.Name, new Dictionary<string, object> { { "placeholder", "Name" } })
        </div>
        <div class="row">
            @Html.TextBoxFor(x => myModel.Email, new Dictionary<string, object> { { "placeholder", "Email Address" } })
        </div>
        <div class="row">
            @Html.TextBoxFor(x => myModel.Website, new Dictionary<string, object> { { "placeholder", "Website" } })
        </div>
        <div class="row tall">
            @Html.TextAreaFor(x => myModel.Comment, new Dictionary<string, object> { { "placeholder", "Comment" } })
        </div>
        <div class="row">
            <input type="submit" id="Submit"  name="Submit" value="Submit" />
        </div>
    }
}

Clicking on Submit button will take me to the controller but the Model is always empty.

My controller is like below:

[HttpPost]
public ActionResult Post(MyViewModel model)
{
    return this.View();
}

Any suggestions? Do I have to add this MyModel properties to current page's ViewData?

役に立ちましたか?

解決

Create a partial-view that takes MyViewModel -- that will be required to make Html.TextBoxFor() work the way you want it to. Then call that partial view from your main view. Let's say you name the view "myForm", and place it in the shared folder. Then in your main view:

@Html.Partial("myForm", myModel)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top