Reputation: 10723
I have one view with a form and I want when a button will be clicked, the same view to be reloaded with new informations from the form's textbox values. The new informations will be found in a database - I'm doing that in the controller.
So, I thought I should call an action method from the view.
But, I read that it is poor practice to transfer data from the view to the cantroller, since MVC is designed especially NOT for that.
Does someone have an idea how to design this?
Upvotes: 2
Views: 1022
Reputation: 60556
The View
is called by the Controller
. You can put a form in your View and send it to your ActionMethod on form submit, for example.
Model
public class ViewModel
{
public string SomeProperty { get; set; }
}
View
@model MvcApplication2.Models.ViewModel;
@using (Html.BeginForm())
{
@Html.TextBoxFor(x => x.SomeProperty)
<input type="submit" />
}
Controller with ActionMethods
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View(new ViewModel());
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
// do something with your model
// load from something from database for example
return View(model);
}
}
Upvotes: 1
Reputation: 375
In addition to what has been said, in order to reload the same view, you might consider using the ajax functionality that MVC provides. Then you will not have to really reload the whole page, but only an element on the page. A very basic examples can be found here
Upvotes: 0
Reputation: 4993
The button click should manifest itself as a HTTP POST to the Controller Action handling the input. The controller will process the input, grab the appropriate information from the database and return the view which will be populated with this new data.
The view should reference the controller action for purposes of determining the address of the HTTP POST, but does not itself pass data to the controller.
Remember that a button click is not handled by the "View" - which is just a template for the rendered HTML - but will instead be handled by the client browser.
Upvotes: 0
Reputation: 4413
Where exactly did you read that it's poor practice to transfer data from the view to the controller? You need to transfer some information to the action to signify what data to fetch.
In your scenario you can use route values to pass an id:
@Html.ActionLink("Get Latest", "GetLatest", new { Id = Model.Id })
Where the view model has an Id
property for the current view's item.
Upvotes: 0