0

Whats the best way to get User Input from the view to controller. I mean specific input not like "FormCollection" someting like "object person" or "int value" and how to refresh the page on certain interval

2 Answers 2

5

By writing a view model:

public class UserViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Controller:

public class UsersController : Controller
{
    public ActionResult Index()
    {
        return View(new UserViewModel());
    }

    [HttpPost]
    public ActionResult Index(UserViewModel model)
    {
        // Here the default model binder will automatically
        // instantiate the UserViewModel filled with the values
        // coming from the form POST
        return View(model);
    }

}

View:

@model AppName.Models.UserViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.FirstName)
        @Html.TextBoxFor(x => x.FirstName)
    </div>
    <div>
        @Html.LabelFor(x => x.LastName)
        @Html.TextBoxFor(x => x.LastName)
    </div>

    <input type="submit" value="OK" />
}
Sign up to request clarification or add additional context in comments.

Comments

0

Say for example if your view is strongly typed with a "Person" class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Then inside your view:

@model MyMVCApp.Person
@using(Html.BeginForm())
{
    @Html.EditorForModel()
    // or Html.TextBoxFor(m => m.FirstName) .. and do this for all of the properties.
    <input type="submit" value="Submit" />
}

Then you'd have an action that would handle the form:

[HttpPost]
public ActionResult Edit(Person model)
{
    // do stuff with model here.
}

MVC uses what are called ModelBinders to take that form collection and map it to a model.

To answer your second question, you can refresh a page with the following JavaScript:

<script type="text/javascript">
// Reload after 1 minute.
setTimeout(function ()
{
    window.location.reload();
}, 60000);
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.