Images not showing when foreach loop working in _PartialView Page - c#

I have a model class like following
public class UserViewModel
{
public UserViewModel()
{
UsersDet = new Dictionary<long, string>();
usrdat = new List<User>();
}
public Dictionary<long , string> UsersDet { get; set; }
public IEnumerable<User> usrdata { get; set; }
}
Then I'm trying to get those model values in partial view like following
this partial view is a popup actually.
_UserView partial view
#model Project.ViewModels.UserViewModel
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body" style="width: 530px;">
<div id="slider_view" style="display: block;">
<div class="flexslider">
<ul class="slides">
#foreach (var item in Model.UsersDet )
{
<li data-thumb="~/Upload_Images/A.jpg">
<img src="~/Upload_Images/A.jpg" data-imagedata="image001" />
<p class="flex-caption">Title</p>
</li>
}
</ul>
</div>
</div>
</div>
</div>
</div>
Here I cannot see the A.jpg images in Popup, but when I use like following I can see images
_UserView partial view
#model Project.ViewModels.UserViewModel
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body" style="width: 530px;">
<div id="slider_view" style="display: block;">
<div class="flexslider">
<ul class="slides">
#for (int i =0; i < 3 ; i ++)
{
<li data-thumb="~/Upload_Images/A.jpg">
<img src="~/Upload_Images/A.jpg" data-imagedata="image001" />
<p class="flex-caption">Title</p>
</li>
}
</ul>
</div>
</div>
</div>
</div>
</div>
this is controller method to bind values to above popup
[HttpGet]
public PartialViewResult MethodName(int id)
{
try
{
IEnumerable<User> listofData = ..
UserViewModel listofimage = new UserViewModel();
if (listofData != null)
{
listofimage.usrdata = listofData;
foreach(var item in listofimage.usrdata)
{
var path = RenderImage(item.ImageValue, "UploadImagePath");
var fileResult = path as FilePathResult;
if (fileResult != null)
{
string imageurl = fileResult.FileName;
imageurl = imageurl.Replace(#"\\", #"\");
listofimage.UsersDet.Add(item.CaseID, imageurl);
}
}
}
return PartialView("_UserView", listofimages);
}
catch (Exception)
{
throw;
}
}
public ActionResult RenderImage(string imageid, string pathvalue)
{
try
{
var URL = System.Configuration.ConfigurationManager.AppSettings[pathvalue].ToString();
var path = Path.Combine(URL, imageid + ".jpg");
return base.File(path, "image/jpeg");
}
catch (Exception)
{
throw;
}
}
Whats is wrong in my foreach approach how to populate elements as loop

If Model.UsersDet is populated with items then < li > elements will be rendered. If they are rendered but you don't see the images then you open the devtools and in the Network tab you look for the requests made for each image. If there requests have bad response then you fixed it according to the returned http status.
But not having the project to debug and if you are saying that #for is working but #foreach is not then the problem should be that the Model.UsersDet is empty.

Related

Not set to an instance of an object? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I get this returned when I try to add a comment. I can not really understand why I get error from create where i want to create a ticket ?
This is the contoller where my error comes from and it points on obj.Ticket.Ticket_Id == 0
public IActionResult Create(TicketVM obj)
{
if (obj.Ticket.Ticket_Id == 0)
{
_db.Tickets.Add(obj.Ticket);
}
else
{
_db.Tickets.Update(obj.Ticket);
}
}
This is the message i get:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
WebApplication20.Models.TicketVM.Ticket.get returned null.
I try to create an application where I can create a project object that then you should be able to create tickets for, and inside my tickets i should be able to make comments for the specific ticket. To be able to do that, I have created a one to many relationship between project --> ticket then a one to many relationship between ticket --> comment.
This is what my ticket controller where im able to create update and delete Tickets look like:
[Authorize]
public class TicketController : Controller
{
private readonly ApplicationDbContext _db;
public TicketController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Ticket> objList = _db.Tickets;
foreach (var obj in objList)
{
obj.Project = _db.Projects.FirstOrDefault(u => u.Project_Id == obj.Project_Id);
}
return View(objList);
}
/**This is the view i want to create my operation on**/
public IActionResult Info(int id)
{
CommentVM t = new CommentVM();
t.Ticket = _db.Tickets.FirstOrDefault(t => t.Ticket_Id == id);
t.Comments = _db.Commenents.Where(f => f.Ticket_Id == id);
return View(t);
}
// Create
public IActionResult Create(int? id)
{
TicketVM obj = new TicketVM();
obj.ProjectList = _db.Projects.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Project_Id.ToString()
});
if (id == null)
{
return View(obj);
}
// Status List
#region
List<SelectListItem> statusList = new List<SelectListItem>();
statusList.Add(new SelectListItem()
{
Value = "Open",
Text = "Open"
});
statusList.Add(new SelectListItem()
{
Value = "Closed",
Text = "Closed"
});
#endregion
// Status List End
if (obj == null)
{
return NotFound();
}
obj.Ticket = _db.Tickets.FirstOrDefault(u => u.Ticket_Id == id);
obj.StatusList = statusList;
return View(obj);
}
/**This is the controller where i get my error from:**/
// POST Create/Update
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(TicketVM obj)
{
if (obj.Ticket.Ticket_Id == 0)
{
_db.Tickets.Add(obj.Ticket);
}
else
{
_db.Tickets.Update(obj.Ticket);
}
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
// Delete
public IActionResult Delete(int? id)
{
var dbObj = _db.Tickets.FirstOrDefault(u => u.Ticket_Id == id);
_db.Tickets.Remove(dbObj);
_db.SaveChanges();
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Comments(CommentVM obj)
{
if(ModelState.IsValid)
{
_db.Commenents.Add(obj.Comment);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View();
}
}
At the bottom I have created a comment controller where I want to be able to add comments to the database. When I try to make a comment from my view that belongs to the InfoController in Ticket, I get an alarm that there is an error in my TicketController from Create / POST where it says 'Object reference not set to an instance of an object.' I do not understand at all why I get an error from Creaste / POST ticket?
This is what my Info view looks like
#model WebApplication20.ViewModel.CommentVM
#{
Layout = "_Dashboard";
var title = "About Ticket";
}
<html>
<body id="page-top">
<div class="card mx-auto" style="width: 18rem;">
<div class="card-header">
<h4><strong>Ticket Status</strong></h4> Created #Model.Ticket.TicketCreated
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item"><strong>Name:</strong>#Model.Ticket.TicketName </li>
<li class="list-group-item"><strong>Descripton: #Model.Ticket.TicketDescription</strong></li>
<li class="list-group-item"><strong>Priority:</strong> #Model.Ticket.TicketPriority</li>
<li class="list-group-item"><strong>Type:</strong> #Model.Ticket.TicketType</li>
<li class="list-group-item"><strong>Status:</strong> #Model.Ticket.TicketStatus</li>
</ul>
</div>
<div class="card shadow mx-auto m-3" style="width: 42rem;">
<div class="card-header">
<h4><strong>Comments</strong></h4>
</div>
<div class="row">
<div class="col-md-4 p-4">
<form asp-action="Comments">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Message" class="control-label"></label>
<input asp-for="Message" class="form-control" />
<span asp-validation-for="Message" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#*TABLE*#
<div class="row">
<!-- Area Chart -->
<div class="col-xl-8 col-lg-7">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Current Comments</h6>
</div>
#if (Model.Comments.Count() > 0)
{
<table class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>
Message
</th>
<th>
Submitter
</th>
<th>
Created
</th>
</tr>
</thead>
<tbody>
#foreach (var comment in Model.Comments)
{
<tr>
<td width="10%">
#comment.Message
</td>
<td width="10%">
</td>
<td width="10%">
#comment.Created
</td>
</tr>
}
</tbody>
</table>
}
else
{
<h5 class="text-secondary m-1">There are no comments for this ticket yet..</h5>
}
</div>
</div>
</div>
#*END TABLE*#
</div>
<div class="text-center p-3">
<a asp-controller="Ticket" asp-route-Id="#Model.Ticket.Ticket_Id" asp-action="Create" class="btn btn-success btn-lg text-white w-30">Edit</a>
<a asp-controller="Ticket" asp-route-Id="#Model.Ticket.Ticket_Id" asp-action="Delete" class="btn btn-danger btn-lg text-white w-30">Delete</a>
</div>
<!-- Bootstrap core JavaScript-->
<script src="/TemplateInfo/vendor/jquery/jquery.min.js"></script>
<script src="/TemplateInfo/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/TemplateInfo/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/TemplateInfo/js/sb-admin-2.min.js"></script>
</body>
</html>
have you checked that TicketVM obj has data. I think your binding is not working and TicketVM obj is set to null. put a breakpoint and check it

How to create dynamic dropdown boxes that grows in ASP.NET EF?

I'm trying to implement dropboxes that can appear prefilled, and can grow dynamically when you press a button. I started with a basic dropdown box implementation that doesn't grow dynamically. This is my controller+DTO code snippet:
public class TaskDTO
{
public string TaskTemplateName { get; set;}
}
public IActionResult Create()
{
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View();
}
public async Task<IActionResult> Create([Bind("Id,TaskTemplateName")] TaskDTO task)
{
if (ModelState.IsValid)
{
//Do some stuff
}
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateName);
return View(task);
}
This is my create.cshtml razor code:
<h2>Create</h2>
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="TaskTemplateName" class="control-label"></label>
` `<select asp-for="TaskTemplateName" class="form-control" asp-items="ViewBag.TaskTemplateId"></select>
</div>
Then I looked around and found this link that shows how to create dynamic forms that can grow. I tried to combine that idea with dropdown boxes. Based on that tutorial, here's my new DTO+controller code:
public class TaskTemplateDTO
{
public string TaskTemplateName { get; set; }
}
public class TaskDTO
{
public List<TaskTemplateDTO> TaskTemplateNames { get; set; }
}
public IActionResult Create()
{
var vm = new TaskDTO() { };
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name");
return View(vm);
}
public async Task<IActionResult> Create([Bind("Id,TaskName,TaskTemplateNames,ParentTasks,IsBasicTask,EstimatedTime,RequiredResources")] TaskDTO task)
{
if (ModelState.IsValid)
{
//Do some stuff
}
ViewData["TaskTemplateId"] = new SelectList(_context.TaskTemplates, "Id", "Name", task.TaskTemplateNames);
return View(task);
}
here's my extra EditorTemplates razor, TaskTemplateDTO.cshtml:
#model Namespace.TaskTemplateDTO
<select asp-for="TaskTemplateName" class="TaskTemplate" asp-items="ViewBag.TaskTemplateId"></select>
This is my create.cshtml razor code:
<h2>Create</h2>
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<table class="table table-bordered" id="TaskTemplateTable">
<tr>
<th>Task Templates</th>
<th><button type="button" name="add" id="btn_AddTaskTemplate" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
#Html.EditorFor(f => f.TaskTemplateNames)
</tr>
</table>
</div>
</form>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
$("#btn_AddTaskTemplate").click(function () {
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate" /></td>';
html += '<td></td></tr>';
});
$('#TaskTemplateTable').append(html);
</script>
}
The code above adds the new dropdowns on click, but the dropdowns aren't prefilled with data, what have I done wrong?
You will need to have the select options that you want in the new controls to be available to your javascript method. There are a few ways to do it, the most straightforward would be to hide it in your html page in a hidden select control.
Your CSHTML:
<h2>Create</h2>
//Added the hidden HTML control here
#Html.DropDownList("hidden-select",
new SelectList((IEnumerable) ViewData["TaskTemplateId"]),
null, new Dictionary<string, object>
{
{ "id", "task-template-names" },
{ "style", "display: none" }
})
<h4>TemplateTask</h4>
<hr />
<div class="row">
<div class="col-md-4">
////other things you were doing
This will render in your html as a prepopulated hidden template from which you can build new dropdowns with options on button click.
$("#btn_AddTaskTemplate").click(function () {
var i = $(".TaskTemplate").length;
var html = '';
html += '<tr>';
html += '<td><select type="text" name="TaskTemplateNames[' + i + '].TaskTemplateName" class="TaskTemplate">';
html += document.querySelector("#task-template-names").innerHTML;
html += '</select></td>';
html += '<td></td></tr>';
});
I wasn't able to test this code because the setup is beyond my scope here, so you might need to tweak it a little bit. If you encounter any difficult errors, let me know.

return RedirectToAction to a Index but with a href sections? (Ajax optional)

I have multiple sections in a single View file, for example, href="#timeline" for <div class="tab-pane" id="timeline">. href="#settings" for <div class="tab-pane" id="settings">
Clicking the tab Timeline will bring you to the tab that shows you a timeline.
Clicking the tab Settings will bring you to the tab that allows you change settings.
How do I return view in the Controlller to a section href="#settings" in the same View file?
Thanks.
Models:
public class UserViewModel
{
public List<Timeline> TheTimeline { get; set; }
public List<Posts> ThePosts{ get; set; }
public string SettingsVM{ get; set; }
}
Controllers:
[HttpPost]
public ActionResult SettingsUpdateProfile(User variable, IFormFile TheEmployeePicture)
{
blablabla
if (UploadFile(TheEmployeePicture, fname))
{
return RedirectToAction(String.Format("Index/{0}", User.Identity.Name);
}
else
{
return BadRequest();
}
}
else
{
return BadRequest();
}
}
else
{
return BadRequest();
}
}
Views:
#model UserProfile.Models.UserViewModel
#{
ViewData["Title"] = "UUUSSSEEERRR";
}
<div class="col-md-9">
<div class="nav-tabs-custom">
<ul class="nav nav-tabs">
<li class="active">Posts</li>
<li>Timeline</li>
<div class="tab-pane" id="timeline">
...
</div>
If you use same ViewModel for both tabs, i recomend don't use ajax, as you don't need more request, if you have enougth data for display.
<ul class="nav nav-tabs in" id="your_id">
<li><a data-toggle="tab" href="#timeline">Time Line</a></li>
<li><a data-toggle="tab" href="#settings">Time Line</a></li>
</ul>
<div id="tab-content" class="tab-content">
<div class="tab-pane" id="timeline">#{ Html.RenderPartial("ViewName", Model)}</div>
<div class="tab-pane" id="timeline">#{ Html.RenderAction("ActionName", "ControllerName", new { routeParams})}</div>
</div>
So you can choose, use render partial and pass model as param and view name or you can Render Action, it will do request and return view.

Model empty on post

When I submit, my model is empty on post.
Model
public QuizModel()
{
Questions = new List<QuizQuestionModel>();
}
public QuizModel(string quizName)
{
QuizName = quizName;
Score = 0;
IntranetEntities db = new IntranetEntities();
Quiz quiz = db.Quizs.Where(x => x.Name.Equals(quizName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (quiz != null)
{
IQueryable<Quiz_Question> questions = db.Quiz_Question.Where(x => x.QuizID.Equals(quiz.ID)).OrderBy(x => x.QuestionNo);
Questions = new List<QuizQuestionModel>();
foreach (Quiz_Question question in questions)
{
QuizQuestionModel q = new QuizQuestionModel();
q.ID = question.ID;
q.Question = question.Question;
q.UserAnswer = null;
q.SystemAnswer = question.Answer;
Questions.Add(q);
}
}
}
public string QuizName { get; set; }
public List<QuizQuestionModel> Questions { get; set; }
public int Score { get; set; }
Controller
[HttpPost]
public ActionResult OSHAQuiz(Models.QuizModel model)
{
if (ModelState.IsValid)
{
bool passed = false;
model.Score = model.Questions.Where(x => x.UserAnswer.Equals(x.SystemAnswer, StringComparison.InvariantCultureIgnoreCase)).Count();
if (!model.Score.Equals(0))
{
double percent = model.Score / model.Questions.Count();
if (percent >= .8)
{
passed = true;
}
}
if (passed)
{
return View("/Views/Quiz/Passed.cshtml");
}
else
{
return View("/Views/Quiz/Failed.cshtml");
}
}
else
{
return View("/Views/Quiz/Quiz.cshtml", model);
}
}
View
#model PAL.Intranet.Models.QuizModel
<script>
$(document).ready(function () {
$("input:checked").removeAttr("checked");
});
</script>
<div class="grid">
<h2>OSHA Quiz</h2>
<hr />
<div class="align-center">
#using (Html.BeginForm("OSHAQuiz", "Quiz", FormMethod.Post, new { id = "formShowLoading" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row cell">
<div class="example bg-grayLighter" data-text="Directions">
<ul class="simple-list">
<li class="align-left">When you have made your selection for all 20 statements, click on the button 'Submit.'</li>
<li class="align-left">Mark 'True' or 'False' for each statement.</li>
<li class="align-left">You must score 80% (16 correct) to pass.</li>
<li class="align-left">You must fill in your full name to receive credit.</li>
</ul>
</div>
</div>
<div class="row cell">
<div class="row cell">
<div class="panel" data-role="panel">
<div class="heading">
<span class="title">Questions</span>
</div>
<div class="content">
<ul class="numeric-list">
#foreach (var question in Model.Questions)
{
<li>
<table class="table hovered" style="width: 100%;">
<tr>
<td align="left">#question</td>
<td align="right" width="150px">
<div class="align-center">
<label class="align-right input-control radio small-check">
#Html.RadioButtonFor(model => question.UserAnswer, true, new { Name = question.GroupName })
<span class="check"></span>
<span class="caption">True</span>
</label>
<label class="align-right input-control radio small-check">
#Html.RadioButtonFor(model => question.UserAnswer, false, new { Name = question.GroupName })
<span class="check"></span>
<span class="caption">False</span>
</label>
</div>
</td>
</tr>
</table>
</li>
}
</ul>
</div>
</div>
</div>
</div>
<div class="row cell">
<input type="submit" value="Submit" class="button info small-button" />
<input type="reset" value="Reset" class="button primary small-button" />
</div>
}
</div>
</div>
UPDATE
if I use HiddenFor on QuizName, it does come back over on post but the rest of the model is empty.
When iterating over a collection that you want to post back to your model, you can't use foreach; you must use a regular for statement with indexing in order for Razor to generate the correct field names.
#for (var i = 0; i < Model.Questions.Count(); i++)
{
...
#Html.RadioButtonFor(m => m.Questions[i].UserAnswer)
}
Then, your fields will have name attributes in the form of Questions[0].UserAnswer, which the modelbinder will recognize and bind appropriately to your model. As you have it now, with the foreach, the field name is being generated as question.UserAnswer, which the modelbinder has no idea what to do with and discards.
Also, FWIW, accessing your context from within your model entity is a hugely bad idea, and even worse if you're not injecting it. Move that logic out of your entity and utilize a utility class or service instead. Also, look into dependency injection, as your context is one of those things that you want one and only one instance of per request. If you start instantiating multiple instances of the same context, you will have problems.
The problem is model binding is going to attempt to bind your form values to properties on your model. It will not use the constructor on your model that takes the quiz name, it will use the default constructor to instantiate the QuizModel object.
I would consider refactoring this model to remove your EntityFramework dependency and find a new way to populate those values.
You should also call the Dispose() method on IDisposable objects when you're done using them.
My suggestion for how to solve this problem would be to use the QuizModel you currently have to help render your view (i.e. Your quiz questions and possible answer for each question).
Create a seperate ViewModel for quiz submission
public class QuizSubmission
{
public string QuizName { get;set; }
public List<QuizQuestionResponse> Responses { get;set; }
}
public class QuizQuestionResponse
{
public int QuestionId { get;set; }
public int AnswerId { get;set; }
}
In your controller action, you should be binding to a QuizSubmission model.
[HttpPost]
public ActionResult OSHAQuiz(Models.QuizSubmission model)
{
Then you'll be able to perform any actions you need for that quiz submission (ie. data access, validation ).
You'll also need to update your view so that your Html input elements have the correct name attributes that model binding can correctly bind each question and response pair to a QuizQuestionResponse item in your Responses list.

Model passed to Partial to View

Been searching around but couldn't find a direct solution to what I'm trying to achieve.
I've tried to include as much as needed but it's a very large project so hopefully you'll get the gist.
Overview:
I have a view model that has several lists of objects within it. I am using two partial views for control over each of the list of objects, one for gathering the list of objects (which is held in a session), and the other for adding a list of said object into the list.
Update:
As per comment - what I am looking to do is as follows - in the Index, fill out the existingIp model info, which is displayed through the addToListPartialView, then it will post to the ListPartialView to update the list through the session, handled backend in the controller, which will in turn display on the Index - the question ultimately is, how do I achieve this?
Problem:
The issue I'm having is once I've added an object, through a partial view, to the object list, another partial view, how do I then pass this back to the main view?
Code:
Controller
public ActionResult AddExistingIp([Bind(Include = "Subnet, Cidr, Mask")]ExistingIp existingIp)
{
if(Session["pa_ipv4Session"] != null)
{
pa_ipv4 pa_ipv4 = (pa_ipv4)Session["pa_ipv4Session"];
if(pa_ipv4.ExistingIps == null)
{
pa_ipv4.ExistingIps = new List<ExistingIp>();
}
pa_ipv4.ExistingIps.Add(existingIp);
ViewBag.pa_ipv4 = pa_ipv4.ExistingIps;
return View("ExistingIpView", ViewBag.pa_ipv4);
}
else
{
pa_ipv4 pa_ipv4 = new pa_ipv4();
Session["pa_ipv4Session"] = pa_ipv4;
pa_ipv4.ExistingIps = new List<ExistingIp>();
pa_ipv4.ExistingIps.Add(existingIp);
ViewBag.pa_ipv4 = pa_ipv4.ExistingIps;
return View("ExistingIpView", ViewBag.pa_ipv4);
}
Index:
#model ViewModel
<div id="ExistingIpList">
#{Html.RenderPartial("ExistingIpView");}
</div>
<div id="addExisting">
#{Html.RenderPartial("AddExistingIp");}
</div>
List Partial
#model IEnumerable<ExistingIp>
#if (Model != null)
{
foreach (var ei in Model)
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>#ei.Subnet</span>
</div>
<div class="ui-block-b">
<span>#ei.Cidr</span>
</div>
<div class="ui-block-c">
<span>#ei.Mask</span>
</div>
<div class="ui-block-d">
#ei.Id
Delete
</div>
</div>
}
}
Add to list partial:
#using (Html.BeginForm("AddExistingIp", "PA_IPV4"))
{
<div class="ui-grid-c ui-responsive">
<div class="ui-block-a">
<span>
#Html.EditorFor(m => m.Subnet)
#Html.ValidationMessageFor(m => m.Subnet)
</span>
</div>
<div class="ui-block-b">
<span>
#Html.EditorFor(m => m.Cidr)
#Html.ValidationMessageFor(m => m.Cidr)
</span>
</div>
<div class="ui-block-c">
<span>
#Html.EditorFor(m => m.Mask)
#Html.ValidationMessageFor(m => m.Mask)
</span>
</div>
<div class="ui-block-d">
<span>
#Html.EditorFor(m => m.Id)
#Html.ValidationMessageFor(m => m.Id)
</span>
</div>
</div>
<div data-role="main" class="ui-content">
<div data-role="controlgroup" data-type="horizontal">
<input type="submit" id="addExistingIp" cssclass="ui-btn ui-corner-all ui-shadow" value="Add" />
</div>
</div>
}
ViewModel:
public Contact ContactDetails { get; set; }
[Required]
public bool ExistingAddress { get; set; }
public List<ExistingIp> ExistingIps { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string ExistingNotes { get; set; }
You can modify the AddExistingIp to just store the data. And to make a RedirectToAction Index. There you will take the data from Session and pass it to the Model.
[HttpPost]
public ActionResult AddExistingIp([Bind(Include = "Subnet, Cidr, Mask")]ExistingIp existingIp)
{
if(Session["pa_ipv4Session"] != null)
{
pa_ipv4 pa_ipv4 = (pa_ipv4)Session["pa_ipv4Session"];
if(pa_ipv4.ExistingIps == null)
{
pa_ipv4.ExistingIps = new List<ExistingIp>();
}
pa_ipv4.ExistingIps.Add(existingIp);
}
else
{
pa_ipv4 pa_ipv4 = new pa_ipv4();
Session["pa_ipv4Session"] = pa_ipv4;
pa_ipv4.ExistingIps = new List<ExistingIp>();
pa_ipv4.ExistingIps.Add(existingIp);
}
return RedirectToAction("Index");
}
The Index Action will look similar with this, where you take data from Session and use it in your Model
public ActionResult Index()
{
var viewModel = new ViewModel();
// take data from Session
pa_ipv4 pa_ipv4 = Session["pa_ipv4Session"] as (pa_ipv4);
// some verification
// add the list from Session to model
viewModel.ExistingIps = pa_ipv4.ExistingIps;
return View(viewModel);
}
Also, I think your Index View you should at ExistingIpView you should pass the Model to display.
#model ViewModel
<div id="ExistingIpList">
#{Html.RenderPartial("ExistingIpView", Model.ExistingIps);}
</div>
<div id="addExisting">
#{Html.RenderPartial("AddExistingIp");}
</div>

Categories

Resources