asp.net mvc dropdownlist with directory files list - asp.net-mvc-4

I want to show all files from a folder "newsletter" with category list. but when I use following code, I got error, my code is :
public ActionResult templatelist()
{
var data = _session.emailForcampaigns.Select(m => m.category).Distinct().AsQueryable();
ViewBag.ddlCategory = new SelectList(data, "category", "category");
return View(Directory.EnumerateFiles(Server.MapPath("~/newsletter")));
}
and i have following lines in view
<table class="tables" >
<tr>
<td>Fiels</td>
<td>
<select id="template" name="template">
#foreach (var fullPath in Model)
{
var fileName = Path.GetFileName(fullPath);
<option value="#fileName"> #fileName</option>
}
</select>
</td>
</tr>
<tr>
<td>Category </td>
<td>
#Html.DropDownList("ddlCategory", null, new { #class = "dropdown " })
</td>
</tr>
</table>
but i am getting error

You forgot to specify a data source for the drop-down list:
#Html.DropDownList("ddlCategory", new SelectList(ViewBag.ddlCategory , "category", "category"))

Related

Update Partial view MVC4

I have this controller:
public ActionResult PopulateTreeViewModel()
{
MainModelPopulate mainModelPopulate = new MainModelPopulate();
// populate model
return View(mainModelPopulate);
}
That has a view like this:
#model xxx.xxx.MainModelPopulate
<table>
#foreach (var item2 in Model.CountryList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item2.CountryName);
</td>
</tr>
foreach (var item3 in item2.BrandList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item3.BrandName);
</td>
</tr>
foreach (var item4 in item3.ProductList)
{
<tr>
<td>
#Html.ActionLink(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
</td>
</tr>
}
}
}
</table>
The FunctionX controller is like this :
public ActionResult FunctionX(int idBrand=1 , int idProd=1)
{
List<ListTypeModel> typeModelList = new List<ListTypeModel>();
// populate typeModelList
return PartialView(typeModelList);
}
}
with this partial view:
#model IEnumerable<TControl.Models.ListTypeModel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
I want to add this partial view in my main view (PopulateTreeViewModel) and update the table with the relative type of product contained in Function X.
I tried also to substitute #Html.ActionLink with #Ajax.ActionLink and it performs the same way.
Have you tried #Html.RenderAction(item4.ProductName, "FunctionX", new { idLab = item3.BrandID, idDep = item4.ProductID });
There are other options too..! Pls refer http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html

Insert Partial View to a another Partial View

This is the main view Dept_Manager_Approval.cshtml where I have put a modal to show data.
<td>
<i title="View Details">
#Ajax.ActionLink(" ", "ViewAccessStatus", new { id = item.request_access_id },
new AjaxOptions
{
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "edit-div",
}, new { #class = "fa fa-eye btn btn-success approveModal sample" })</i>
</td>
In this partial view which just a modal, ViewAccessStatus.cshtml , I have inserted in here another partial view.
<div>
<h2><span class ="label label-success">Request Creator</span> </h2>
#if (Model.carf_type == "BATCH CARF")
{
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
}else{
<h4><span class ="label label-success">#Html.DisplayFor(model=>model.created_by)</span></h4>
}
</div>
COntroller:
public ActionResult Batch_Requestor1(int id = 0)
{
var data = db.Batch_CARF.Where(x => x.carf_id == id && x.active_flag == true).ToList();
return PartialView(data);
}
Batch_Requestor1.cshtml
#model IEnumerable<PETC_CARF.Models.Batch_CARF>
#{
ViewBag.Title = "All Requestors";
}
<br/><br/>
<table class="table table-hover">
<tr class="success">
<th>
#Html.DisplayName("Full Name")
</th>
<th>
#Html.DisplayName("Email Add")
</th>
<th>
#Html.DisplayName("User ID")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.fname) - #Html.DisplayFor(modelItem => item.lname)
</td>
<td>
#Html.DisplayFor(modelItem => item.email_add)
</td>
<td>
#Html.DisplayFor(modelItem => item.user_id)
</td>
</tr>
}
</table>
When I run this, I've got this error
The model item passed into the dictionary is of type '<>f__AnonymousType01[System.Int32]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[PETC_CARF.Models.Batch_CARF]'.
Any ideas how will I insert another partial view?
#Html.Partial() renders a partial view. It does not call an action method that in turn renders the partial. In your case
#Html.Partial("Batch_Requestor1", new {id= Model.carf_id })
is rendering a partial view named Batch_Requestor1.cshtml and passing it a model defined by new {id= Model.carf_id } (and anonymous object) but that view expects a model which is IEnumerable<PETC_CARF.Models.Batch_CARF>.
Instead, you need to use
#Html.Action("Batch_Requestor1", new {id= Model.carf_id })
which calls the method public ActionResult Batch_Requestor1(int id = 0) and passes it the value of Model.carf_id, which will in turn render the partial view.

MVC 4 - Return error message from Controller - Show in View

I am doing a C# project using Razor in VS2010 (MVC 4).
I need to return an error message from Controller to View and show it to the user.
What I have tried:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
ModelState.AddModelError("error", "adfdghdghgdhgdhdgda");
ViewBag.error = TempData["error"];
return RedirectToAction("Form_edit", "Form");
}
VIEW:
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary("error")
#Html.ValidationMessage("error")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Please help me to achieve this.
The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
if(ModelState.IsValid())
{
--- operations
return Redirect("OtherAction", "SomeController");
}
// here you can use a little trick
//fill the model property that holds the information for the dropdown with the data
// you haven't provided the get method but it should look something like this
model.Countries = ... some data goes here;
model.dd_value = ... some other data;
model.dd_text = ... other data;
ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
return View(model);
}
and then in the view just use :
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#Html.ValidationSummary(true)
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
This should work okay.
If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.
other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
TempData["error"] = "someErrorMessage";
return RedirectToAction("form_Post", "Form");
}
[HttpGet]
public ActionResult form_edit()
{
do stuff here ----
ViewData["error"] = TempData["error"];
return View();
}
#model mvc_cs.Models.FormModels
#using ctrlr = mvc_cs.Controllers.FormController
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
<div>#ViewData["error"]</div>
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
<table>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
}
Thanks for all the replies.
I was able to solve this by doing the following:
CONTROLLER:
[HttpPost]
public ActionResult form_edit(FormModels model)
{
model.error_msg = model.update_content(model);
return RedirectToAction("Form_edit", "Form", model);
}
public ActionResult form_edit(FormModels model, string searchString,string id)
{
string test = model.selectedvalue;
var bal = new FormModels();
bal.Countries = bal.get_contentdetails(searchString);
bal.selectedvalue = id;
bal.dd_text = "content_name";
bal.dd_value = "content_id";
test = model.error_msg;
ViewBag.head = "Heading";
if (model.error_msg != null)
{
ModelState.AddModelError("error_msg", test);
}
model.error_msg = "";
return View(bal);
}
VIEW:
#using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{
<table>
<tr>
<td>
#ViewBag.error
#Html.ValidationMessage("error_msg")
</td>
</tr>
<tr>
<th>
#Html.DisplayNameFor(model => model.content_name)
#Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")
</th>
</tr>
</table>
}
If you want to do a redirect, you can either:
ViewBag.Error = "error message";
or
TempData["Error"] = "error message";
You can add this to your _Layout.cshtml:
#using MyProj.ViewModels;
...
#if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert #message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>#message.Title</strong>
#message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.

Html.ActionLink object parameters + MVC4

I am calling Edit action from my view that should accept an object as parameter.
Action:
[HttpPost]
public ActionResult Edit(Organization obj)
{
//remove the lock since it is not required for inserts
if (ModelState.IsValid)
{
OrganizationRepo.Update(obj);
UnitOfWork.Save();
LockSvc.Unlock(obj);
return RedirectToAction("List");
}
else
{
return View();
}
}
From View:
#foreach (var item in Model) {
cap = item.GetValForProp<string>("Caption");
nameinuse = item.GetValForProp<string>("NameInUse");
desc = item.GetValForProp<string>("Description");
<tr>
<td class="txt">
<input type="text" name="Caption" class="txt" value="#cap"/>
</td>
<td>
<input type="text" name="NameInUse" class="txt" value="#nameinuse"/>
</td>
<td>
<input type="text" name="Description" class="txt" value="#desc"/>
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Organization", new { obj = item as Organization }, null)
</td>
</tr>
}
It is raising an exception: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'PartyWeb.Controllers.Internal.OrganizationController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Can somebody advise how to pass object as parameter?
Can somebody advise how to pass object as parameter?
Why are you using an ActionLink? An ActionLink sends a GET request, not POST. So don't expect your [HttpPost] action to ever be invoked by using an ActionLink. You will have to use an HTML form and include all the properties you want to be sent as input fields.
So:
<tr>
<td colspan="4">
#using (Html.BeginForm("Edit", "Organization", FormMethod.Post))
{
<table>
<tr>
#foreach (var item in Model)
{
<td class="txt">
#Html.TextBox("Caption", item.GetValForProp<string>("Caption"), new { #class = "txt" })
</td>
<td class="txt">
#Html.TextBox("NameInUse", item.GetValForProp<string>("NameInUse"), new { #class = "txt" })
</td>
<td class="txt">
#Html.TextBox("Description", item.GetValForProp<string>("Description"), new { #class = "txt" })
</td>
<td>
<button type="submit">Edit</button>
</td>
}
</tr>
</table>
}
</td>
</tr>
Also notice that I used a nested <table> because you cannot have a <form> inside a <tr> and some browser such as IE won't like it.

Call post edit action from Razor view mvc4

This question might have been asked several times, however it is not working in my case, so please bear with me.
I have the below actions in my controller:
[HttpPost]
public ActionResult Edit(Organization obj)
{
if (ModelState.IsValid)
{
OrgRepo.Update(obj);
return RedirectToAction("Details");
}
else
return View();
}
public ActionResult Edit(int id)
{
return View();
}
I am trying to update the data into database by calling post edit action.
For this purpose, I am calling the edit action as below:
#foreach (var item in Model) {
var test = item.PartyId;
<tr id="#test">
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.Caption)"/>
</td>
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.NameInUse)"/>
</td>
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.Description )"/>
</td>
<td>
#using (Html.BeginForm())
{
#Html.ActionLink("Edit", "Edit", "Org", null, new { #obj = item })
}
</td>
</tr>
However when I click on edit I am getting exception:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'Dwiza.Controllers.OrgController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
My questions:
How can I fix this?
Why it get edit action is getting invoked instead of post edit?
What are better ways to invoke edit action among invoke through jQuery, or ajax or any others, if you can suggest better ways of doing it?
The #Html.ActionLink produces an a tag which can only be used to call GET. Change to a submit button to get a POST.
Normally with an Edit, you are only editing a sinble model rather than a collection on a page but going with what you have, change the cshtml to:
#model ICollection<Organization>
<table>
#foreach (var item in Model)
{
using (Html.BeginForm())
{
var test = item.PartyId;
<tr id="#test">
<td class="txt">
<input type="text" name="Caption" class="txt" value="#item.Caption"/>
</td>
<td class="txt">
<input type="text" name="NameInUse" class="txt" value="#item.NameInUse"/>
</td>
<td class="txt">
<input type="text" name="Description" class="txt" value="#item.Description" />
</td>
<td>
<input type="hidden" name="PartyId" value="#item.PartyId"/>
<button type="submit">Edit</button>
</td>
</tr>
}
}
</table>
Now each table row is wrapped by a form meaning the submit button will post that data. The name attribute on the inputs will cause the MVC model binders to bind your posted values to your model correctly.
This hidden input at the end will ensure your PartyId value gets posted back. The fact that it is in int (and not nullable) was giving the exception with your initial code I think.
HTH
EDIT
Adding controller code (note - I still think this is a little/lot strange as you should be editing only the one Organisation...
public ActionResult Edit(int id)
{
// get your organisations from your orgRepo... I'm mocking that out.
var orgs = new List<Organization> { new Organization { PartyId = 1, Description = "Org 1", Caption = "Caption 1", NameInUse = "Name 1"},
new Organization { PartyId = 2, Description = "Org 2", Caption = "Caption 2", NameInUse = "Name 2"}};
return View(orgs);
}
lordy, that is a mess dude. your form only has a link in it, and that link is to the edit action, that will invoke a get, the form will never post back. are you trying to do a form inside a table row?
#foreach (var item in Model) {
var test = item.PartyId;
<tr>
<td colspan ="4>
#using (Html.BeginForm("Edit", "Org", FormMethod.Post))
{
#Html.HiddenFor(modelItem => item.PartyId)
<table>
<tr id="#test">
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.Caption)"/>
</td>
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.NameInUse)"/>
</td>
<td class ="txt">
<input type="text"class="txt" value="#Html.DisplayFor(modelItem => item.Description )"/>
</td>
<td>
<input type="submit" value="edit" />
</td>
</tr>
</table>
}
</td>
</tr>
}
That code will do an edit inside a row, but i am just guessing at the structure from the code you posted.