简体   繁体   中英

Razor view not sending input to controller?

I am using a razor file for my view with this post form:

@using (Html.BeginForm("Save", "MyEventController", FormMethod.Post))
{
    <md-input-container class="md-block" flex-gt-xs="">
        <label>Title</label>
        <input type="text" name="title" />
    </md-input-container>

        <md-input-container class="md-block">
            <label>Address</label>
            <input type="text" name="address" id="txtAddress">
        </md-input-container>


        <md-button class="md-raised">
            <input type="submit" value="Save" />
        </md-button>
}

I want to send my input to my controller in Controllers/EventController.cs as show below:

public class MyEventController : Controller
{
    [HttpPost]
    public void Save(FormCollection collection)
    {            
        InputEvent y = new InputEvent();
        y.title = collection["title"];
        y.address = collection["address"];
    }
}

The Save() methods seems to never be called. how do i submit to Save()?

I am developing in Visual Studio 2015

Remove the text "Controller" when you specify the controller. Change it to,

Html.BeginForm("Save", "MyEvent", FormMethod.Post)

Remove the word "Controller" from your second parameter "MyEventController". So it should be "MyEvent".

Furthermore, I would create a Model (M from MVC) and when the form is posted, instead of receiving FormCollection, it will receive a nice model instead. ASP MVC will take care of binding for you.

Also, as others have pointed out, you may want to eventually return something back to the client to specify if the form submission and processing was successful. Therefore, your action should not return void. Most of the time in cases such as this, you should use the PRG pattern-it is very important to use this pattern.

Try ActionResult instead of void .

From MSDN :

Writes an opening tag to the response. When the user submits the form, the request will be processed by an action method.

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