Passing model from view to controller - asp.net-mvc-3

After Learning Jon Galloways MVC Music Store Example.I Just didn't understood the create view How to pass model to controller in which we could see it from parameter in the action Create(Movie movie). Thanks.
[HttpPost]
public ActionResult Create(Movie movie)
{
if (ModelState.IsValid)
{
db.Movies.Add(movie);//Where is the movie come from?
db.SaveChanges();
return RedirectToAction("Index");
}
return View(movie);
}

In the code example you have posted, the Movie model will be created through model binding. During this process any of your form variables will be matched up with the object specified in the action.
For instance the value of
<input type="text" name="Title"/>
would be assigned to movie's Title property.
A view can be associated with a model by declaring (Razor syntax)
#model GallowaySample.Movie

Normally you do not pass the model to the controller, but you create an instance of your model in your controller.

Related

Return a view from Post method

I have this post method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Invitations(SuperInvitationsEditModel model)
{
...
var newmodel = new SuperInvitationsEditModel();
if (hasErrors)
{
SuperInvitationsErrorModel newErrorModel = new SuperInvitationsErrorModel();
newErrorModel.Errors = model.Errors;
return View(newErrorModel);
}
return View(newmodel);
}
When this code in the if(hasErrors) executes I get this error.
The model item passed into the dictionary is of type 'MyProject.Models.SuperInvitationsErrorModel', but this dictionary requires a model item of type 'MyProject.Models.SuperInvitationsEditModel'.
I thought I can do this since the return value of the method is a generic ActionResult. Can anyone tell me why is this not working?
because your current view is strongly typed. change the code as
return View("yourviewname",newErrorModel);
It has nothing to do with casting ViewResult to ActionResult. The problem is, that you have strongly typed view that expects the model of type SuperInvitationsEditModel (see #model on the top of Invitations.cshtml), but you are passing the model of type SuperInvitationsErrorModel to it.
You should merge the two view model classes (SuperInvitationsEditModel and SuperInvitationsErrorModel) into one, or create a standalone view for each of them.

How to Post Partial View Data?

Any input much appreciated :)
I want to know one thing whether I can post multiple partial views data in MVC?(means i want to update partial views data to DATABASE)
Here is the Example:
Model:-
public class PassengerViewModel
{
public List<PassengerModel> Passengers { get; set; }
public ContactModel Contact { get; set; }
}
Controller:-
[RequiredAuthentication]
public ActionResult Passenger()
{
var passengrViewMdl = new PassengerViewModel()
{
Contact = new ContactModel(),
Passengers = psngrService.LoadPassengers(Convert.ToInt32(Session["LPORefNO"]))
};
return View(passengrViewMdl);
}
[HttpPost]
public ActionResult Passenger(PassengerViewModel passengerViewModel)
{
Here i want to update Passengers & Contact information
}
View:-
#model QR.LPO.Core.Models.PassengerViewModel
#{
ViewBag.Title = "Add Passengers";
}
#using (Html.BeginForm())
{
#Html.Partial("_Passenger", Model.Passengers);
#Html.Partial("_PassengerContact", Model.Contact);
<input type="submit" value="Submit" />
}
Thanks.
Yes, indeed you can, but, controller usually works only with one model per request, so either your model should have declared within it properties of both partial submodels, or submodels themselves.
This is possible due to HTML specifications, all data on form, which has submit buttom is send to submit action url.
This will almost work as you have it - there's nothing inherent to partials that would prevent this, in the end the html that's output is all that's important.
The problem with your code is that presumably the model of your _Passenger view is of type Passengers and the model of your _PassangerContact view is of type Contact. What this means is that if you standard HtmlHelper extensions (like Html.Textbox(...) or Html.TextboxFor(...) the fields they generate will not have full names like Contact.Name, but instead just names relative to their model, like Name. This will cause modelbinding to fail in your post action.
You can solve this in a number of ways.
Simply use the same model type (PassengerViewModel) in your sub-views, and write code like #Html.TextboxFor(m => m.Contact.Name).
Instead of using Html.Partial, use Html.EditorFor(...). This passes the proper prefix information into the child view so the field names are generated properly.
Explicitly set the prefix yourself
Like this:
#{
var childViewData = new ViewDataDictionary(this.ViewData);
childView.TemplateInfo.HtmlFieldPrefix = "Contact";
}
#Html.Partial("_PassengerContact", Model.Contact, childViewData)
You could also look at creating a Html.PartialFor overload yourself, as described in this stackoverflow question: ASP.NET MVC partial views: input name prefixes

Binding model to view issue

I have my own model classes, which are public, but when making a view, I cannot find the model itself in the list of models to bind to. Why is this? Can I bind the model to the view somehow afterwards?
Thanks
Add the following to the top of your View:
#model your.namespace.YourModelClass
Then your controllers' action method needs to return an appropriate instance of YourModelClass:
public ActionResult Index(){
return View(new YourModelClass());
}

How to update database by attaching model to DataContext

I am building a web site using MVC 3 Framework.I have a Linq to SQL DataContext to handle data access.According to what I've learned you can use a post method to get the form information when a user submits a form and MVC frmaework can map the data to a model object.
something like this :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Entity model)
But I have problem with attaching this model object to the data context object here's what I am doing :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Entity model)
{
if(ModelState.IsValid)
{
_dataContext.Attach(model);
_dataContext.SubmitChanges();
return RedirectToAction("Index");
}
return View("Edit", model);
}
But nothing happens.What am I doing wrong ?
The problem is that your _dataContext doesn't know that your entity has been changed.
So you would have to use the overload that sets modified as true:
_dataContext.Attach(model, true);

Access HiddenFor(Model=>Model.Id) MVC ASP.NET in Controller

How do I access the following written in View
#Html.HiddenFor(Model=>Model.id)
in Controller
?
Thank you
Create a Action method that takes the Type that you used as Model in your view.
[HttpPost]
public ActionResult Create(MyModel model)
{
var id = model.id;//the id in #Html.HiddenFor(Model=>Model.id)
}

Resources