do not partial view loads from the parent view - asp.net-mvc-3

I have a parent view and a partial view, but when it try to load the partial view from the parent view get the following error
The model item passed into the dictionary is of type 'System.Data.Objects.DataClasses.EntityCollection`1[RolMVC3.Models.OFFICE]',but this dictionary requires a model item of type 'RolMVC3.Models.OFFICE'.
partial view:
#model RolMVC3.Models.OFFICE
#Html.HiddenFor(model => model.IdOffice)
#Html.HiddenFor(model => model.IdSCampus)
<div class="editor-label">
#Html.LabelFor(model => model.AddressOffice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressOffice)
#Html.ValidationMessageFor(model => model.AddressOffice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneOffice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model..PhoneOffice)
#Html.ValidationMessageFor(model => model..PhoneOffice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailOffice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailOffice)
#Html.ValidationMessageFor(model => EmailOffice)
</div>
parent view:
#model RolMVC3.Models.CAMPUS_UNIVERSITY
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<h2> #ViewBag.University.Name - #ViewBag.Campus.NameCity </h2>
<fieldset>
<legend>MODIFY OFFICE</legend>
#Html.HiddenFor(model => model.IdUniversidty)
#Html.HiddenFor(model => model.IdCityCampus)
#Html.HiddenFor(model => model.IdCampus)
<div class="editor-label">
#Html.LabelFor(model => model.AddressCampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AddressCampus)
#Html.ValidationMessageFor(model => model.AddressCampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneCampusSede)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneCampus)
#Html.ValidationMessageFor(model => model.PhoneCampus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EamailCampus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EamailCampus)
#Html.ValidationMessageFor(model => model.EamailCampus)
</div>
<fieldset>
<legend>DATA</legend>
#Html.Partial("_Office", Model.OFFICE)
</fieldset>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
controller:
public ActionResult Edit()
{
decimal id;
id = (decimal)Session["Offi"];
ViewBag.University = (from c in db.OFFICE
join s in db.CAMPUS_UNIVERSITY on c.IdCampus equals s.IdCampus
join u in db.UNIVERSIDTY on s.IdUniversity equals u.IdUniversity
where c.IdOffice == id
select u).Single();
ViewBag.Campus = (from c in db.OFFICE
join s in db.CAMPUS_UNIVERSITY on c.IdCampus equals s.IdCampus
join ci in db.CIUDAD on s.IdCaityCampus equals ci.IdCity
where c.IdOffice == id
select ci).Single();
OFFICE office = db.OFFICE.Single(c => c.IdOffice == id);
CAMPUS_UNIVERSITY campus_university = db.CAMPUS_UNIVERSITY.Single(s => s.IdSede == office.IdCampus);
return View(campus_university);
}
blessings

Can you show what RolMVC3.Models.OFFICE and CAMPUS_UNIVERSITY objects look like? I'm guessing your CAMPUS_UNIVERSITY model has something weird going on in it. Is the .OFFICE field tightly cast as an OFFICE object or is it an enumerable? You could probably test this out quickly by passing in Model.OFFICE[0] in the view.

Your controller has the code
OFFICE office = db.OFFICE.Single(c => c.IdOffice == id);
CAMPUS_UNIVERSITY campus_university = db.CAMPUS_UNIVERSITY
.Single(s => s.IdSede == office.IdCampus);
But your View is ONLY using the model CAMPUS_UNIVERSITY. I would assume that the CAMPUS_UNIVERSITY.Office property is a EntityCollection<OFFICE> which does not match the view's requirement of Office.
One solution is to display all the offices:
#foreach(var office in Model.OFFICE)
{
#Html.Partial("_Office", office)
}
or the other is to actually use the Office you created in the controller
Controller (add)
ViewBag.Office = db.OFFICE.Single(c => c.IdOffice == id);
View (change)
#Html.Partial("_Office", ViewBag.Office)

It looks like you are passing a differnt type than what is expecting. From your view, i could undestand that the view is expecting an object of type "OFFICE". Are you sure the modal you are passing to the Partial View call is of same type ? Or are you passing a List of Offices ?

Related

Display message using view bag without refreshing view

I have a view A From ControllerA Which has two buttons 1. Create 2. Update
Upon clicking update or Create its opening a new partial viewB As popup from another controller B.
What iam trying to get is If a record is created successfully in b I am now closing the popup. Apart from closing the popup I want to display a message in view A.
I am trying like this:
Controller B
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
And in the view A:
#if(ViewBag.Message!=null)
{
#ViewBag.Message
}
View B:
#model DreamTrade.Web.BL.ViewModels.ProjectViewModelNew
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout_Popup.cshtml";
}
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#jqgprojectnew').text("Record added successfully");//jqgprojectnew is the name of grid in view A
</script>
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Project</legend>
#Html.HiddenFor(model => model.ProjectID)
<div class="editor-label">
#Html.LabelFor(model => model.ProjectDetail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectDetail)
#Html.ValidationMessageFor(model => model.ProjectDetail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectRef)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectRef)
#Html.ValidationMessageFor(model => model.ProjectRef)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProjectName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProjectName)
#Html.ValidationMessageFor(model => model.ProjectName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatusList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ProjectStatusId,new SelectList(Model.StatusList,"SourceStatusId","Description"),"Please Select")
#Html.ValidationMessageFor(model => model.ProjectStatusId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CustomerList)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Id,new SelectList(Model.CustomerList,"Id","Name"),"Please Select")
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<div>
Back to list
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
please let me know where iam doing wrong
Include a label field where you want to show the message.
<label id=mylabel></label>// Add this before jqgrid
Modify the code to:
#if (ViewBag.RecordAdded != null && (bool)ViewBag.RecordAdded)
{
<script type="text/javascript">
parent.$.nmTop().close();
$('#mylabel').text("Record added successfully");
</script>
}

Selected item list and other object

I'm new in asp.net mvc3 programming and I'm trying to build a specific form. I need to have a form with the user field (which I have) but also a list of object (in that case SStatus).
My form :
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Création d'utilisateur</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Lastname)
#Html.ValidationMessageFor(model => model.Lastname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Firstname)
#Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Login)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Login)
#Html.ValidationMessageFor(model => model.Login)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>Status</p>
#{
//The error was form here
#{
var list = ViewBag.listStatus as List<SStatus>;
}
#if (list != null)
{
foreach(var status in list)
{
<option value=#status.ID>#status.Name</option>
}
}
</select>
}
<p>
<input type="submit" value="Création" />
</p>
</fieldset>
}
The list call :
public ActionResult CreateUserView()
{
RestClient client = new RestClient(Resource.Resource.LocalUrlService);
RestRequest request = new RestRequest("/status/all", Method.GET);
var response = client.Execute(request);
if(response.StatusCode == HttpStatusCode.OK)
{
List<SStatus> listSatus = JsonHelper.FromJson<List<SStatus>>(response.Content);
ViewBag.listStatus = listSatus;
}
return View();
}
And the form post:
[HttpPost]
public ActionResult CreateUserView(Uuser userToCreate, string list)
{
//list got the ID of SStatus.
if (ModelState.IsValid)
{//Stuff}
}
So the question is : How get the selected list item ?
Regards.
Use a view model pattern. I still don't see how your Uuser object is sent to the view (via the default [HttpGet] action, but I think I see what you're trying to accomplish.) If you refactor this way, you'll still get to use the built-in validation, automagic model binding, etc.
public class CreateUserViewModel
{
public Uuser User { get; set; }
public string Status { get; set; }
}
Then your action parameter should be of type CreateUserViewModel e.g.
[HttpPost]
public ActionResult CreateUserView(CreateUserViewModel vm)
{
if(ModelState.IsValid)
{
{//Stuff}
}
I believe you'll need a name attribute on the <select> element in order for it to be posted.
<p>Status</p>
#{
<select name="Status">
Although, you're going to run into trouble if the model isn't valid. Your view should be strongly typed against CreateUserViewModel e.g.
#model YourModelNamespace.CreateUserViewModel
So, your Lastname property might look like this (note the .User)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Création d'utilisateur</legend>
<div class="editor-label">
#Html.LabelFor(model => model.User.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.User.Lastname)
#Html.ValidationMessageFor(model => model.User.Lastname)
</div>
And finally, I guess you could keep the possible list of status in the ViewBag, but you'll want to set the selected value to #Model.Status. You may want to consider changing CreateUserViewModel.Status to a List<SelectListItem> that you can populate from your controller e.g. your GET action should return View(CreateUserViewModel)
public ActionResult CreateUserViewModel()
{
CreateUserViewModel vm = new CreateUserViewModel();
vm.User = // set user
vm.Status = new List<SelectListItem>()
{
new SelectListItem()
{
Value = "status1",
Text = "status 1",
Selected = false
},
new SelectListItem()
{
Value = "status2",
Text = "status 2",
Selected = true
},
};
return View(vm); // this is the correct way to strongly type your view
}

Main View eliminates a filter after I create an element from a partial view

Mi trouble is this: I have a View called "Create" it refers to the creation of promotions. Each promotion has Genres according to the user, so, when I do enter to the "create promotions" I have a list (dropdown) with the genres of the user, but if there is no an adecuate genre I must create it without leaving the current page, so I used a partial view for creating new genres and I inserted it in the main view (Create promotions) It do works, but after the genre is created, the main view shows ALL the genres and not only those who correspond to the current user.
This is the main view:
#model Points2Pay.Models.Promocion
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script type="text/javascript">
$(document).ready(function () {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function () {
$(".slidingDiv").slideToggle();
});
});
#using (Html.BeginForm())
{
Show/hide
<div class="slidingDiv" id="partialView">
#{Html.RenderAction("Create2", "Genre");}
</div>
}
#using (Html.BeginForm("Create","StoreManager"))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Promocion</legend>
<div class="editor-label">
#Html.LabelFor(model => model.GenreId, "Genre")
</div>
<div class="editor-field" id="DROPDOWN">
#Html.DropDownList("GenreId", String.Empty)
#Html.ValidationMessageFor(model => model.GenreId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Puntos)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Puntos)
#Html.ValidationMessageFor(model => model.Puntos)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PromocionArtUrl)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PromocionArtUrl)
#Html.ValidationMessageFor(model => model.PromocionArtUrl)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>`
THIS IS THE SECONDARY VIEW
#model Points2Pay.Models.Genre
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<legend>New Genre</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Create new Genre" />
</p>
}
AND THIS IS THE CONTROLLER
[ChildActionOnly]
public ActionResult Create2()
{
return PartialView("Create2");
}
//
// POST: /Genre/Create2
[HttpPost]
public ActionResult Create2(Genre genre)
{
var ComercioActual = (Guid)System.Web.Security.Membership.GetUser().ProviderUserKey;
if (ModelState.IsValid)
{
genre.ComercioId = ComercioActual;
db.Genres.Add(genre);
db.SaveChanges();
return PartialView("Create2");
}
return PartialView("Create2");
}
Hope you can help me.

ASP.Net MVC 3 how to UpdateUser account?

i want to update user account in my project. i have a view like this :
#using (Html.BeginForm("edit/" + #Model.SysUsers[0].UserID, "cpanel/sysuser",
FormMethod.Post))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>#Model.SysUsers[0].UserID</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SysUsers[0].UserName)
#Html.ValidationMessageFor(model => model.SysUsers[0].UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserEmail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SysUsers[0].UserEmail)
#Html.ValidationMessageFor(model => model.SysUsers[0].UserEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserComment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SysUsers[0].UserComment)
#Html.ValidationMessageFor(model => model.SysUsers[0].UserComment)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserLocked)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SysUsers[0].UserLocked)
#Html.ValidationMessageFor(model => model.SysUsers[0].UserLocked)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserApproved)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SysUsers[0].UserApproved)
#Html.ValidationMessageFor(model => model.SysUsers[0].UserApproved)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SysUsers[0].UserOffice)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SysUsers[0].UserOffice, new
SelectList(Model.GetawayOffice, "OfficeCode", "OfficeDesc",
Model.SysUsers[0].UserOffice))
#Html.ValidationMessageFor(model => model.SysUsers[0].UserOffice)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
and the controller is like this :
public ActionResult Edit(string id)
{
model.SysUsers = repo.SelectSystemUser(id).ToList();
model.Office = reps.Office().ToList();
return View(model);
}
[HttpPost]
public ActionResult Edit(string id, FormCollection collection)
{
//update in System_User Table
Guid UserId = new Guid(id.ToString());
var SysUser = db.System_User.Single(s => s.User_UserId == UserId);
SysUser.User_Office = collection["SysUsers[0].UserOffice"];
//update aspnet_membership, like comment, email, isLocked, isApproved
...
}
i can update Office in Sytem_User table, but how can I update aspnet_membership (its for updting comment, email, isLocked, isApproved) ?
i think that i must use
membership.UpdateUser(MembershipUser User)
but can someone give me an example how to use membership.UpdateUser ?
now i can update user comment and user email, i use this :
var usermembership = Membership.GetUser(UserId);
usermembership.Comment = collection["SysUsers[0].UserComment"];
Membership.UpdateUser(usermembership);
usermembership.Email = collection["SysUsers[0].UserEmail"];
Membership.UpdateUser(usermembership);
but, i cant update user locked and user approve. how to update thoose ?
thank you
Membership.UpdateUser Method
Updates the database with the information for the specified user.
MembershipUser u = Membership.GetUser(User.Identity.Name);
u.Email = someValue;
Membership.UpdateUser(u);
Have a look at http://msdn.microsoft.com/en-us/library/system.web.security.membership.updateuser.aspx
Possible dupe of ASP.Net MVC 3 Membership.UpdateUser(MembershipUser user)
Hmm - I think you are on the right track. Perhaps have a look around for examples of apps that use membership.
Here I am using WebForms to change a password:
user = Membership.GetUser(txtUsername.Text);
string generatedPassword = user.ResetPassword();
user.ChangePassword(generatedPassword, txtPassword.Text);
Good luck.
I think a way would be the one to write your onw membershipuser implementation.
Look at this post "How to: Implement a Custom Membership User".
If you don't like to implement every method you can create a descendant class and write only the methods you need to behave differently, then declare your new provider in the web.config

mvc 3 partial view with Ajax.BeginForm not working (posting to new form arrgh)

I have a mvc 3 form with 2 columns. The left column is a treeview and when a node is selected the div with id='partialView' is updated to show the details of that node. This appears to be work ok.
The edit form (which is a partial view) is loaded in the div with id='partialView'.
Now the problem occurs when the user submits this partial view...now it does post back to the controller and the correct method HOWEVER the result is not returned to the div with id='partialView' but posts to a new page.
So this is the scenario where I want the partial view to post and return back replacing the existing partial view.
Is this possible?
I am including my code below for my partial view...
#model DataModel.Code
#using (Ajax.BeginForm("Edit", "Code", new AjaxOptions {
UpdateTargetId = "partialView",
HttpMethod="POST"
}
)) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Code</legend>
#Html.HiddenFor(model => model.CodeID)
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Note)
#Html.ValidationMessageFor(model => model.Note)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DateModified)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DateModified)
#Html.ValidationMessageFor(model => model.DateModified)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TopicID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TopicID)
#Html.ValidationMessageFor(model => model.TopicID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Special)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Special)
#Html.ValidationMessageFor(model => model.Special)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Html)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Html)
#Html.ValidationMessageFor(model => model.Html)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#Html.Telerik().ScriptRegistrar().jQuery(true)
<script type="text/javascript">
$(document).ready(function () {
});
</script>
Include
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
in your _Layout.cshtml

Resources