How do I render HTML from the Viewbag using MVC4 - asp.net-mvc

I need to pass a form element into an MVC4 view using ViewBag. The Viewbag is a list of 1 or more records for each user. The issue is nothing is being passed.
controller
// grab all records for user id 26000.
var qry = db.users.Where(m => m.user_id == "26000").ToList();
foreach (var myBag in qry)
{
// place all the items in the Viewbag.
ViewBag.myItems = "<input type='text' name=#ViewBag.myBag value=#ViewBag.myBag>";
}
view
#using (Html.BeginForm("Index", "Home"))
{
foreach (var item in ViewBag.myBag)
{
<label for="#item">#item</label>
<input type="checkbox" name="#item" value="#item"/>
}
<input id='btnSubmit' type="submit" value='submit' />
}

Controller (the query should really be in your Model).
ViewBag.myItems = db.users.Where(m => m.user_id == "26000").ToList();
View
#using (Html.BeginForm("Index", "Home"))
{
foreach (var item in ViewBag.myItems)
{
<input type="text" name="#item.user_id" value="#item.user_name">
}
<input id='btnSubmit' type="submit" value='submit' />
}

Related

Data not loading on partial view, MVC

I am doing work on form where user can enter a customer record....View is scaffold with Create controller.
On 'Create' View, user can enter 'engineNo' to check its details which passes to another action "CheckRecord",,it can be seen from view...
<form>
<input type="text" id="enginNo" />
<input type="button" value="search" id="btnSearch" />
</form>
#using (Html.BeginForm("Index","Home",FormMethod.Get))
{
#Html.AntiForgeryToken()
<div id="info">
#{Html.RenderAction("CheckRecord","Sales");}
</div>
some create fields
}
The Create and "CheckRecord" actions are,,
public ActionResult Create()
{
ViewBag.CustomerId = new SelectList(db.CustomersDMs, "CustomerId", "Name");
ViewBag.SMClientBranchId = new SelectList(db.SMClientBranchesDMs, "SMClientId", "Name");
ViewBag.EngineNumber = new SelectList(db.StockDMs, "EngineNumber", "ChasisNumber");
return View();
}
public ActionResult CheckRecord(string enginNo)
{
var results = db.StockDMs.Where(c=>c.EngineNumber ==enginNo);
return PartialView("_part",results);
}
And my partialview,,,
#model IEnumerable<SM.CRM.AutosLoan.Models.Core.DomainModels.StockDM>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.AutoCompanyBrand.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.SMClientBranch.Name)
</td>
}
My problem is, the partial view is rendered correctly but the Model of partial view doesn't have value,,,Why is that, i am doing something wrong...Please help,,,Thanks for your time
(Posting this as answer since I mentioned it in comments and that's not the correct place)
Your action CheckRecord(string enginNo) takes an argument of enginNo, but you're calling it without any argument. That in turn means your db lookup will most likely not return any results, unless you get results on..
var results = db.StockDMs.Where(c => c.EngineNumber == null);
Make sure the action gets a valid argument, for example:
#{ Html.RenderAction("CheckRecord", "Sales", new { enginNo = "abc123" }); }

How to display labels and textboxes with the help of model properties in MVC5 razor view with html helpers?

I am not able to create labels and textboxes using model in my view with html helpers.
My View Syntax:
#using (Ajax.BeginForm("RoomsAvail",new AjaxOptions
{
UpdateTargetId = "RoomsAvailData",
InsertionMode ="InsertionMode.Replace"
}))
{
<input type='text' id="Checkin" class="form-control datepicker" />
<input type='text' id="Checkout" class="form-control datepicker" />
<button type="submit" value="Search"></button>
}
#model IEnumerable<RoomAvailabilitySummary>
<div>
#Html.LabelFor(model=>model.ARRDAT)
</div>
<div>
#Html.EditorFor(model=>model.Name)
</div>
My Model
public class RoomAvailabilitySummary
{
public string ARRDAT{get;set;}
public string Name{get;set;}
}
After doing like this, my view is not rendering the model properties into my view to display text for labels and getting the error as "Syste.Collection.Generic.IEnumerable does not contain the definiton for ARRDAT"
Why i am not able to render model property in my html helper to display the name with the help of html helper?
And also i want to access my model values in controller. How can i do this?
Your model is:
#model IEnumerable<RoomAvailabilitySummary>
And you trying to access Name in IEnumerable:
<div>
#Html.EditorFor(model=>model.Name)
</div>
You should use foreach if it is IEnumerable OR just #model RoomAvailabilitySummary if it is not IEnumerable
Added:
Something like this should work:
#model IEnumerable<RoomAvailabilitySummary>
#if(Model.Count() > 0)
{
<div>
#Html.LabelFor(model=>Model.First().Name)
</div>
}
#foreach (var item in Model)
{
<div>
#Html.EditorFor(model=>item.Name)
</div>
}
I think u are trying to iterate over the model (list):
#model IEnumerable<RoomAvailabilitySummary>
#Html.LabelFor(model => model[0].Name)
#foreach(var room in Model)
{
<br />
#Html.EditorFor(x => room.Name)
}

Uploading a file will pass a null object

I have the following _CreateOrEditPartial partial view which contain a text & a file upload:-
#model TMS.Models.DataCenter
#* This partial view defines form fields that will appear when creating and editing entities *#
#Html.AntiForgeryToken()
<div>
<span class="f">Name </span>
#Html.EditorFor(model=>model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div>
<span class="f">Data Center Picture </span>
<input type="file" name="DataCenterfile" />
</div>
and the following main view :-
#using (Html.BeginForm("Create","DataCenter", FormMethod.Post))
{
#Html.ValidationSummary(true)
#Html.Partial("_CreateOrEdit", Model)
<input type="submit" value="Create" class="btn btn-primary"/>
}
Which will call the following ActionMethod:-
[HttpPost]
[ValidateAntiForgeryToken]
[CheckUserPermissions(Action = "Edit", Model = "DataCenter")]
public ActionResult Create(DataCenter dc, HttpPostedFileBase DataCenterfile)
{
// Verify that the user selected a file
if (DataCenterfile != null && DataCenterfile.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(DataCenterfile.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
DataCenterfile.SaveAs(path);
}
but the datacenterfile will always be null .. can anyone advice what is causing this problem?
Thanks
You forgot to add the enctype attribute to your form.
Something like this:
#using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
About enctype attribute: What does enctype='multipart/form-data' mean?

mvc4 razor return empty model on httpget

I would like to return empty model on httpget in a mvc4 razor view. I'll be fetching the model on httppost once the user will select the value from a dropdownlist.
This is what I have:
[HttpGet]
public ActionResult AddNewAgent()
{
var modelAgentt = _fe.Agents.Take(1);
SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new {COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME}), "COUNTER", "FullName", null);
ViewBag.Agent= sl;
return View(agg);
}
Then at HttpPost I have:
[HttpPost]
public ActionResult AddNewAgent(int? LamcomAgents)
{
var modelAgent = _fe.Agents.Take(10);
SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new { COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME }), "COUNTER", "FullName", null);
ViewBag.Agent= sl;
if (LamcomAgents != null && LamcomAgents != 0)
{
return View(modelAgent);
}
return View(modelAgent);
}
The proper linq query is not still included in the httppost action but I'll do that later, i just want to know how I can pass nullable model for the httpget at the first run without getting error in the view.
This is what I have in the view:
#model IEnumerable<Company.Agents>
#{
ViewBag.Title = "AddNewAgent";
}
<h2>Add New Agent</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<p>Agents in System #Html.DropDownList("Agent", String.Empty) <input type="submit" name="Get Agent" value="Get Agent" title="Get Agent" id="btnGetAgent" /></p>
<legend>Agents</legend>
<table>
<tr>
<th>#Html.DisplayNameFor(model => model.A_FirstName)</th>
<th></th>
</tr>
<tr>
</tr>
#foreach(var item in Model)
{
<tr><td>
#Html.DisplayFor(modelItem => item.A_FirstName)
</td></tr>
}
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Thanks in advance, Laziale
Assuming that modelAgentt is of type IEnumerable<Company.Agents>
I think you need to pass modelAgentt to view instead of agg
So change your code from in Get Method
return View(agg);
to
return View(modelAgentt);

ASP.Net MVC 3 Dictionary Binding

Hello I have a model object defined in an MVC 3 project that has a Dictionary property as follows:
MyObj.ObjDictionary<string,string>
I have two controller methods, one which handles returning the view and another that handles the POSTed form from the view
public ActionResult Scanner(string val_1, string val_2, string val_3)
{
//Fetch sessionObj from Model
MyObj sessionObj = getSessionObj(val_1, val_2, val_3);
//At this point model.ObjDictionary<string,string> contains data
return View(sessionObj);
}
[HttpParamAction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Scanner(MyObj model)
{
//At this point model.ObjDictionary<string,string> is null
//i.e. binding is not being properly achieved
//Validate POSTed data
}
In the View, I iterate through each key-value pair (kvp). It has to be done this way since the property is dynamic and I have no way of knowing how many dictionary values there will be.
#using (Html.BeginForm("Action", "Home"))
{
#foreach (var kvp in Model.ObjDictionary)
{
<span>#Html.Label("Scan " + #kvp.Key)</span>
<span>#Html.TextBox(kvp.Key, "", new { #style = "font-size:Medium;width:400px;" })</span>
}
<input type="submit" name="Cancel" value="Cancel" />
<input type="submit" id="Scanner" name="Scanner" value="Scanner" />
}
The goal is to provide a way for users to input data and have that data bound to the values of the specific key. My problem is that the Model.ObjDictionary is null when it gets POSTed. I'm not sure what I'm doing wrong, I read over this article, but this assumes pre-existing values in a dictionary. Is there a way the ModelBinder can bind the data, entered by a user, to a dictionary value mapped to a specific key?
The article you referenced answers your question, you simply need to provide the correct names for your controls, try:
#using (Html.BeginForm("Action", "Home")) {
var i = 0;
foreach (var kvp in Model.ObjDictionary)
{
#Html.Hidden("ObjDictionary[" + i + "].Key", kvp.Key)#kvp.Key
<span>#Html.TextBox("ObjDictionary[" + i + "].Value", kvp.Value, new { #style = "font-size:Medium;width:400px;" })</span>
i++;
<br />
}
<input type="submit" value="Submit" />
}
For dictionaries, each entry should have one field for the key and one field for the value.
#using (Html.BeginForm("Action", "Home"))
{
var index = 0;
#foreach (var kvp in Model.ObjDictionary)
{
<span>#Html.Hidden("ObjDictionary[" + index + "].Key", kvp.Key)
<span>#Html.Label("Scan " + #kvp.Key)</span>
<span>#Html.TextBox("ObjDictionary[" + index + "].Value", kvp.Value, new { #style = "font-size:Medium;width:400px;" })</span>
index++;
}
<input type="submit" name="Cancel" value="Cancel" />
<input type="submit" id="Scanner" name="Scanner" value="Scanner" />
}
By the way, I have encapsulated this functionality in an HTML helper class. You can find it and a working demonstration here: https://github.com/ErikSchierboom/aspnetmvcdictionaryserialization

Resources