I have UserControl as well as Model for particular view. Usercontrol is working properly at the same time i try to include radiobutton on the same view with model. I am getting the Error:"The model item passed into the dictionary is of type 'System.Data.DataTable', but this dictionary requires a model item of type "MyModelName"".
So can you please help anyone.
thanks,
Mohan
The Exception Message is very descriptive and says it all. your view accepts a different model and you are passing different model to this view in controller.
Look at two places
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AcceptedModel>" %>
and in your controller you would have something like
public ActionResult action()
{
SentModel model = new SentModel();
return View(SentModel); //i believe typeof(SentModel) != typeof(AcceptedModel) that is what is causing problem
}
Edit you can use viewModel that can contain all values required by the view
public class MYViewModel
{
System.Data.DataTable MyTable{get;set;}
Registration Myregistration{get;set;}
}
now in controller you can populate your viewModel like
public ActionResult MyActionResult(int id)
{
MyViewModel mdl = new MyViewModel();
mdl.Myregistration = new Registration();
mdl.MyTable = //code to populate table
return View(mdl);
}
and in the view you should update it to accept MyViewModel type
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyViewModel>" %>
and then you can access them in view using
<%foreach( var row in Model.MyTable){}%>
and <%:Model.MyRegistration.FirstName%>
Related
I have a Controller/ShoppingCart which has a Action Method Index() and I created a Index View Page which is strongly type and uses a model class
Project.Models.ShoppingCartViewModel
I have an another Controller/Details which has an Action Method Confirm() and I created a Confirm View Page which is also a strongly type and uses a model class
Project.Models.Confirm
Now all I want to do is that Create a Partial View of Index() which will use a #model Project.Models.ShoppingCartViewModel and display this partial page on right side of Confirm View Page. Both are strongly typed view.
You should add a new property to Confirm view model of type ShoppingCartViewModel
public class Confirm
{
public ShoppingCartViewModel Cart {set;get;}
//Other Properties of your viewmodel goes here
}
Now in the Confirm view, Call the Html.Partial helper method to render the Partial view which displays shopping cart and pass the Model.Cart property.
#model Project.Models.Confirm
<h2>Confirm order</h2>
#Html.Partial("~/Views/ShoppingCart/_CartPartial.cshtml".Model.Cart)
Assuming your partial view is located at ~/Views/ShoppingCart/_CartPartial.cshtml location.
Make sure you properly initialize the Cart property to avoid Null Reference exception (Object reference not set to an instance of object)
public ActionResult Confirm()
{
var vm = new Confirm();
vm.Cart= new ShoppingCartViewModel();
// Load the Shopping cart property values to vm.Cart
return View(vm);
}
I have a Parent View with 2 partial views inside it, the partial views contains few textbox and a button, when I submit the button, the partial views will show some message. Code below :
View :
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of Test.ParentModels)" %>
<% Html.RenderPartial("LogIn", Model.LoginModel)%>
<% Html.RenderPartial("Register", Model.RegisterModel)%>
Model :
public class LoginModel
{
//code here
}
public class RegisterModel
{
//code here
}
public class ParentModel
{
public LoginModel LoginModel {get; set;}
public RegisterModel RegisterModel {get; set;}
}
Controller :
//LogIn page will call this method on submit
public LogIn(LoginModel model)
{
//do something that changed Login html view
return View("LogIn", model);
}
The problem is I don't know how to return the updated partial view along with its parent (postback) and I don't want to use ajax to achieve this. I tried both return View("LogIn", model) and return PartialView("LogIn", model), both only shows the partial view without its parent. Any help will be appreciated and sorry for bad english.
Since you want to do a full page postback, though you postback from the partialview part, in the corresponding Action Method you need to return the Main View(which has two partials in your case) and also capture whatever state required from postback and set it to the model object ( if you need to persist the state) as expected by the Main View.
E.g.
return View("ParentViewName",objParentModel);
I am a real beginner at ASP.NET and working with MVC2 + EF4 in Visual Studio 2010.
I am trying to use the MVVM pattern and strongly typing my View to a ViewModel.
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="True" CodeBehind="~/Views/Options/Index.aspx.cs" Inherits="System.Web.Mvc.ViewPage<OptionsViewModel>" %>
My OptionsViewModel looks like this:
public class OptionsViewModel
{
public List<DeskPreference> DeskPreferences { get; set; }
public List<DayPreference> DayPreferences { get; set; }
}
In the controller I create a new OptionsViewModel and do return View(myOptionsViewModel);
Then, for example, I want to check/uncheck some boxes based on what is in DayPreference. I don't get how to access the model from my code behind file, which looks like this:
using System.Web.Mvc;
using DeskRota_v1.ViewModels;
public class OptionsPage : System.Web.Mvc.ViewPage<OptionsViewModel>
{
protected void Page_Load(object sender, EventArgs e)
{
setCheckBoxes();
}
private void setCheckBoxes()
{
foreach (DayPreference dayPreference in Model.DayPreferences)
{
\\ check boxes here
}
}
It comes up with "The name 'Model' does not exist in the current context". Also if I try to do <% Model. %> in the view there is no intellisense, which I thought there should be. Could somebody please explain what I am doing wrong? How am I supposed to access the ViewModel and its properties?
Your controller will have two overloads of each action method for each view that you need to post back: one with an HttpGet signature and one with an HttpPost signature. The GET version will be called on the first load of the page and will set the initial page values.
The POST version will be called on form submit and accept your viewmodel as an arg. MVC will automagically reconstruct it with the values that were posted in your form (assuming you're using relatively simple types. More complex types is doable but more complicated).
My own convention is to have a work unit in the ViewModel that is responsible for persisting or otherwise processing the values that were submitted. Do NOT put this sort of thing in the controller.
Your viewmodel will need a parameterless constructor, which is the version MVC will use when reconstituting it on page submit. In general I also have a second constructor I use on the GET version so that the VM can instantiate it's initial values.
[HttpGet]
public ActionResult Index(int somethingICareAbout)
{
return View(new IndexViewModel(somethingICareAbout));
}
[HttpPost]
public ActionResult Index(IndexViewModel viewModel)
{
viewModel.SaveChanges()/DoWork()/Whatever();
return View(new viewModel());
}
This is a topic which has been rehashed over and over, I'm still not comfortable on how all the pieces fit together: ViewPage/ViewMasterPage, ViewPage.Model, so forth.
I've entered an undertaking where model data must be passed to both the MasterPage and the ViewPage that derives from it. The data that is passed down need not be shared between the MasterPage and ViewPage, in case that matters.
The solution I ended up with feels like a bit of a hack-job:
1. I abstracted the Controller and overrode the OnActionExecuted Method: The MasterViewPage accesses its data using ViewMasterPage.Model
protected override void OnActionExecuted(ActionExecutedContext filterContext) {
ViewData.Model = new CPanelViewData() { Errors = Errors, Warnings = Warnings, Notifications = Notifications };
base.OnActionExecuted(filterContext);
}
2. I use the Controller.View(string viewName, object model) in my Action Method: The ViewPage is made generic, ie ViewPage< FileManagerViewPage >
public class FileManagerControlPanelController : CPanelController
{
private FileManagerViewPage viewPage = new FileManagerViewPage();
public ActionResult AddFolder(string name, string path) {
...
...
return View("Index", viewPage);
}
All that being said, I wonder if this solution is legitimate. Is there a better way to serve Model data to the MasterPage and View?
For the sake of those who end up in the same situation as me, I'll elaborate on the solution I settled with.
1. I created an abstract class which represents the Master View Model.
public abstract class CpFileMgrMasterViewModel { ... }
2. I created an inherited class which represents the View Page Model.
public class CpFileMgrViewModel:CpFileMgrMasterViewModel { ... }
3. I created an abstract, generic controller which provides methods which handle the Master Model and accepts the View Model type as TModel.
public abstract class CpFileMgrController<TModel>:Controller
where TModel: class, new()
{
private TModel _model = new TModel();
public TModel Model{ get{ return _model; } }
public CpFileMgrController() {
ViewData.Model = _model;
}
}
4. I placed both the Master View and View Page in to their generic form, using the two classes above:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<CpFileMgrMasterViewModel>" %>
<%# Page Language="C#" MasterPageFile="~/Views/Shared/....Master"
Inherits="System.Web.Mvc.ViewPage<CpFileMgrViewModel>" %>
How do I retrieve the value of a textbox in asp.net mvc to store the value on to some variable?
I have a textbox like this <%=Html.TextBox("testbox") %> on the index view page.
I have a button like this <input type="submit" />
I'm using the default view page which comes when you open a new mvc app.
Thanks.
In your controller;
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(FormCollection collection)
{
String g = collection["textFieldname"]
}
or you could use;
TryUpdateModel(modelName);
The above is the prefered solution. If you need more info on TryUpdateModel then post a comment and I'll flesh it out for you.
EDIT:
Rather than explain it let me simply show you;
In your controller:
public class MyFormViewModel
{
public string myInput {get; set;}
}
public ActionResult Search()
{
MyFormViewModel fvm = new MyFormViewModel();
return View(fvm);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(FormCollection collection)
{
MyFormViewModel fvm = new MyFormViewModel();
TryUpdateModel<MyFormViewModel>(fvm);
string userInput = fvm.myInput;
}
Then in your view;
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<YOURNAMESPACE.Controllers.MyFormViewModel>" %>
<%= Html.TextBox("myInput", Model.myInput) %>
Notice two things.
The page is inheriting from your model/class defined in the controller. Not the best place for it but as an example it'll do.
The other thing is that the text box is name the same as the property in the model. In this case myInput.
When the controller does UpdateModel it'll reflection the thing out and match up the textbox name with the name of the field within your form view model.
Make sense?
EDIT 2
Also don't forget to wrap the button and your field in a;
<% using (Html.BeginForm()) {%>