using a usercontrol on aspx page in MVC using partial view - asp.net-mvc

I have Dropdown and on click of a button, I want to display data in the usercontrol
the below code is not working as expected.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%
using (Html.BeginForm())
{%>
<%=Html.DropDownList("CarMake", (SelectList)ViewData["CarMake"])%>
<input type="submit" value="Get all car model" />
<%
Html.RenderPartial("CarModel");
} %>
</asp:Content>
// in controller
public ActionResult Test1()
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test1(int carMake)
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
var carModel = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
return PartialView("CarModel", carModel);
}

Since you're doing a full post of the form, you don't want to return a partial view. You want to set the ViewData["CarModel"] to the correct model, then re-render the same view. The RenderPartial in the view will use this to "include" the correct partial view in the code.
Note this would be different if you were posting via AJAX. At that point, you'd have it set up to replace a particular element of the page and you would want to only render the partial that goes into that element.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test1(int carMake)
{
ViewData["CarMake"] = new SelectList(_carDataContext.Makes.Select(m => new { ID = m.Id, Name = m.Name }), "ID", "Name");
ViewData["CarModel"] = _carDataContext.Models.Where(m => m.MakeId == carMake).ToList();
return View();
}

Related

Html.HiddenFor with preset value

This part was sloved thanks to Ethan Brown
I want to set the value of my Html.HiddenFor helper with preset value
This is my code :
<%: Html.HiddenFor(model => model.idv, new { #value = ViewBag.id })%>
<%: Html.HiddenFor(model => model.etat, new { #value = "false" })%>
But when execute my code i get the error that model.idv and modele.etat are null.
This is seconde part no sloved till now :
This is my action :
public ActionResult Reserver(string id)
{
var model = new Models.rservation
{
idv = id,
etat = false
};
return View(model);
}
[HttpPost]
public ActionResult Reserver(Models.rservation model)
{
if (ModelState.IsValid)
{
entity.AddTorservation(model);
entity.SaveChanges();
return View();
}
else
{
return View(model);
}
}
And this is my view page :
<% using (Html.BeginForm("Reserver", "Home", FormMethod.Post, new { #class = "search_form" })) { %>
//some code textbox to fill
<input type="submit" value="Create" />
<% } %>
So when i click on submit button the model.idv is set again on null value
The correct way to set a preset value is to pass it in via the model (MVC appears to ignore the "value" parameter if you set it). To accomplish what you're looking for, in your action:
public ActionResult MyAction() {
var model = new MyModel {
idv = myPresetId,
etat = false
};
return View( model );
}
Then you don't have to do anything in your view except have:
<%: Html.HiddenFor( model => model.idv ) %>
<%: Html.HiddenFor( model => model.etat ) %>

MVC2 html dropdownlist is invisible

I am just trying to populate a html.dropdown list using mvc2 in VS2008.
But the control is not displayed at all.
Here is my code
public ActionResult Index()
{
ViewData["Time"] = DateTime.Now.ToString();
var mdl = new List<SelectListItem>();
mdl.Add(new SelectListItem
{
Value = "1",
Text = "Module One"
});
mdl.Add(new SelectListItem
{
Value = "2",
Text = "Module Two"
});
ViewData["moduleList"] = new SelectList(mdl,"Value", "Text");
return View("MainMenu");
}
and here is the markup
<div>
<%Html.DropDownList("moduleList", (IEnumerable<SelectListItem>)ViewData["moduleList"]); %>
</div>
Where did i go wrong ?
You are best putting that stuff in your model so for example
in the controller
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewData["Time"] = DateTime.Now.ToString(CultureInfo.InvariantCulture);
var mdl = new List<SelectListItem>
{
new SelectListItem
{
Value = "1",
Text = "Module One"
},
new SelectListItem
{
Value = "2",
Text = "Module Two"
}
};
ViewData["moduleList"] = new SelectList(mdl, "Value", "Text");
var model = new HomeModel
{
SelectedItem = 1,
items = mdl
};
return View(model);
}
}
Now create the model
namespace MvcApplication1.Models
{
public class HomeModel
{
public int SelectedItem { get; set; }
public IEnumerable<SelectListItem> items { get; set; }
}
}
your page will look like this on a test site
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.HomeModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: ViewData["Message"] %></h2>
<p>
To learn more about ASP.NET MVC visit http://asp.net/mvc.
</p>
<div>
<%=Html.DropDownList("SelectedItem", Model.items)%>
</div>
</asp:Content>
Now an explanation, you have created a model for the view and this model is returned to the page by the controller the page is inheriting from a ViewPage which takes the generic argument of the model that was supplied to it by the controller
The markup is saying "give me a html drop down and mark the selected item as the first selected, the items come from the model (which is what your controller supplied it).
In the real world the data would come from your data layer and not directly in the controller (I like as little code in the controller as possible)
edit:
You have a typo for your example try this
<%= Html.DropDownList("moduleList") %>

How to show two Partials view data on Index.cshtml MVC3?

I have created a web application in mvc3 and created two partial views
one having controls two dropdownlist.
second having webgrid which shows data from database.
partialview1.cshtml
#model Mapping.Models.SecurityIdentifierMapping
#using (Html.BeginForm("Mapping", "Home"))
{
#Html.DropDownList("SecurityID", Model.PricingSecurityID, "-- Select SecurityID --")
<br />
#Html.DropDownList("CUSIPID", Model.PricingSecurityID, "-- Select CUSIPID --")
<br />
<button type="submit">Map</button>
}
partialview2.cshtml
#model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
#{
ViewBag.Title = "Mapping";
WebGrid grid = null;
if (Model.Count() > 0 ){
grid = new WebGrid(source: Model,
defaultSort: "Id",
canPage: true,
canSort: true,
rowsPerPage:20);
}
}
<h2>Mapping</h2>
#if (grid != null)
{
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("", header: null, format: #<text>#Html.ActionLink("Edit", "Edit", new { id = (int)item.id }) #Html.ActionLink("Delete", "Delete", new { id = (int)item.id })</text>),
grid.Column("PricingSecurityID"),
grid.Column("CUSIP")
)
)
}
<br />
<p>
#Html.ActionLink("Back", "Index")
</p>
in index.cshtml
<div>
#Html.Partial("_ControlsPartial",)
</div>
<div>
#Html.Partial("_WebGridPartial")
</div>
inside Indexcontroller.cs in Index()
public ActionResult Index()
{
//FOR POPULATE DROPDOWN
//SecurityIdentifierMapping objModel = new SecurityIdentifierMapping();
//objModel.PricingSecurityID = objRepository.GetPricingSecurityID();
//objModel.CUSIP = objRepository.GetCUSIP();
//return View(objModel);
//FOR DISPLAY DATA IN WEBGRID
return View(dbContext.SecurityIdentifierMappings);
}
here problem is webgrid partial view is having#model IEnumerable<Mapping.Models.SecurityIdentifierMapping>
and
controlpartilview is having #model Mapping.Models.SecurityIdentifierMapping
so HOW CAN I CREATE A VIEWMODEL.cs A NEW CLASS WHICH WILL HAVE BOTH MODELS AND HOW CAN I WRITE IT IN INDEX(() SO THAT THAT METHOD WILL POPULATE DROPDOWN ALSO AND SHOW DATA IN WEBGRID ALSO ?
Why not just create a custom View Model class that contains two properties:
public class SecurityIdentifierMappingViewModel
{
public IEnumerable<SecurityIdentifierMapping> MappingList {get; set; }
public SecurityIdentifierMapping Mapping {get; set; }
}
Then you can pass this custom view model to the Index view and the corresponding property as the view model of each of the partials
EDIT
Your Index action would then look something like this:
public ActionResult Index()
{
// single mapping
var mapping = new SecurityIdentifierMapping();
maping.PricingSecurityID = objRepository.GetPricingSecurityID();
mapping.CUSIP = objRepository.GetCUSIP();
var viewModel = new SecurityIdentifierMappingViewModel
{
Mapping = mapping,
MappingList = dbContext.SecurityIdentifierMappings.ToList()
};
return View(viewModel);
}
And in Index.cshtml:
#model SecurityIdentifierMappingViewModel
<div>
#Html.Partial("_ControlsPartial", Model.Mapping)
</div>
<div>
#Html.Partial("_WebGridPartial", Model.MappingList)
</div>

MVC Ajax partial view not updating

I cannot get the partial view to update. If I refresh the page manually, I do see the incremented count. I tried similar approach without partial view inside the countDiv with action returning a random integer and the countDiv was getting updated just fine, so its something about the partial view:
Main view:
#using (Ajax.BeginForm("AddPositive", new RouteValueDictionary { { "id", Model.Id } },
new AjaxOptions() { UpdateTargetId = "countDiv"}))
{
<div>
<input type="submit" value="For" />
</div>
}
<div id="countDiv">
#Html.Partial("PollCounts")
</div>
PollsCounts partial view:
#model MyProj.Models.Poll
<div>Positive: #Model.PositiveCount</div>
<div>Negative: #Model.NegativeCount</div>
Action:
public PartialViewResult AddPositive(int id)
{
Poll poll = db.Polls.Find(id);
db.Entry(poll).State = EntityState.Modified;
poll.PositiveCount++;
db.SaveChanges();
return PartialView("CountsPartial", poll);
}
look in your action, you're returning the countsPartial instead of the pollsCount partial view

Why is my ASP.NET MVC Edit Form not retaining data?

On my edit view, the information doesn't seem to be displayed on the form in the textboxes. Any idea why this is happening? Any help would be greatly appreciated.
Here's how my edit functions inside the controller look like:
[HttpGet]
[Authorize(Roles = "Admin")]
public ActionResult Edit(int id)
{
var logic = new ContactBUS();
var user = logic.GetContact(id);
var mUser = Membership.GetUser(user.Username);
bool memUserExists = doesUserExist(mUser);
if (memUserExists)
{
var model = new RoleListViewModel
{
AllRoles = Roles.GetAllRoles().ToList()
};
return View(model);
}
return View(logic.GetContact(id));
}
[HttpPost]
[Authorize(Roles = "Admin")]
public ActionResult Edit(Contact contact)
{
var logic = new ContactBUS();
if (ModelState.IsValid)
{
logic.EditContact(contact);
return RedirectToAction("List");
}
else
return View(contact);
}
}
Edit.cshtml:
#model ContactWeb.Models.RoleListViewModel
<h2>Edit</h2>
<div style="float:left;width:350px;">
#{Html.RenderPartial("Form", new ContactWebLibrary.Contact());}
</div>
and Form.cshtml:
#model ContactWebLibrary.Contact
#using (Html.BeginForm()) {
<input type="hidden" value="#Model.Id" />
<fieldset id="ContactEditor">
<legend>Fields</legend>
<div>
#Html.LabelFor(c=>c.FirstName, "First Name")
#Html.TextBoxFor(c=>c.FirstName)
#Html.ValidationMessageFor(c=>c.FirstName)
</div>
<div>
#Html.LabelFor(c=>c.LastName, "Last Name")
#Html.TextBoxFor(c=>c.LastName)
#Html.ValidationMessageFor(c=>c.LastName)
</div>
...
<input type="submit" value="#(Model.Id == 0 ? "Create" : "Edit" )" />
</fieldset>
}
If memUserExists is true then a new RolesListViewModel is passed to the Edit view. This in turn passes a brand new Contact model to the partial view each time this partial view is rendered:
#{Html.RenderPartial("Form", new ContactWebLibrary.Contact());}
So the contact used in the partial will not contain any information to display, hence, no values are being displayed.
Does logic.GetContact(id) return a RoleListViewModel? Otherwise, when memUserExists is false, I don't think the following line would work when returning the Edit view:
return View(logic.GetContact(id));
And also, the following line in your [HttpPost]:
return View(contact);
This passes a Contact object to a view that is expecting a RoleListViewModel.
Hope this helps.

Resources