C# MVC 5 - How To Get a Table In a Partial View - c#

I'm trying to make a HTML table with a checkbox column where this checkbox column is from a ViewModel:
public string FirstName ...
public string LastName ...
public bool Checked ...
I want to get the List<ViewModel> and pass it to the controller, using a Partial View, to verify the checked columns, because I want to delete the checked lines.
If I wanted to get the checked columns in the same controller, I do, but in a different controller, I don't. In my case, this 'Partial View' is a BS Modal.

What you need is a partial rendered through Ajax. You call the action method from a modal using load and POST the form data so it removes checked lines. You can call any controller you need from this, all you need is:
$('#target').load('#Html.Url("Action", "Controller")');
And on submit:
$('#targetform').submit(function (e) {
var data = JSON.stringify($(e.currentTarget).serialize());
$.post('#Html.Url("Action", "Controller")', data, function (html) {
$('#target').html(html);
});
e.preventDefault();
});

Related

Modelstate not updating value from JSON through Jquery POST

Basically I get a value from a dropdownlist and pass it to a client method through AJAX. Based on this value, I get data, which I want to put into a textbox.
<script type="text/javascript">
$('#dropdownlist').change(function () {
$.post('/Index/GetJSON/' + this.value, null,
function (data) {
$('#somefield').val(data)
});
});
</script>
So this method gets called:
[HttpPost]
public JsonResult GetJSON(int ID)
{
return Json(data);
}
Markup
#Html.EditorFor(m => m.somefield)
somefield does change it's value visually. But it does not get updated when I inspect it's value. It's as if val(data.ID) doesn't register to the model. Due to my code, I can't call ModelState.Clear() either...
The reason I use this approach, and not Ajax.Form and partial views, is because I have all the markup inside a HTML.BeginForm (which is submitted) with many different dropdownlists interacting through textboxes through AJAX, and you cannot nest Ajax.Form with HTML.BeginForm. Thus I cannot submit changes to the model through the Ajax.Form and call ModelState.Clear().
.val() sets the value property of an element if you want the change to be reflected in the elements value attr use .attr()
$('#somefield').attr('value', data)

Multiple models with ID in one view

Working on this project and I am stuck again. I have a view that I need to display a menu along the side. The menu is pulled from a table. Along the side of this, I have a question that is pulled from another table. Inside of this, there will be suggestions that are yet pulled from another table. With the question, I have a couple of inputs, radio buttons, and a text box for feedback which will end up in a different table. All of this has to take place with the ID from the main table so that when the information is saved in the results table it knows what the main record it belongs too. The page can be brought up with a /Audit/302 but when you change the submenu to the next question how do you get that question and maintain the ID. For Every question, there will be an entry for that ID. I have made relationships this is what it looks like.
August 02 2011
I have added a ViewModel that pulls a list of checkboxes from a table called Score (OK, Concern, N/A)
The page that i have is rendered with an ID it pulls a record from AuditSchedules and retrieves some info. In the Layout i also have a side menu (partial) that renders a list of actionlinks that will select different sections and a MainQuestion (partial). We work up to this point. Since i have added the viewModel to populate the checkboxes and save the text into a table with the ID of the AuditSchedule and MainQuestion. My issue is i am calling for id to select the ids from the table for the Scores and it is grabbing the id from the AuditSchedule. Giving me a no data found.
Here is my Controller:
//get
public ActionResult _Forms(int score)
{
AuditFormEdit viewModel = new AuditFormEdit();
viewModel.ScoreInstance = _db.Scores.Single(r => r.ScoreID == score);
viewModel.InitializeScoreCheckBoxHelperList(_db.Scores.ToList());
return View(viewModel);
}
//post
[HttpPost]
public ActionResult _Forms(int score, AuditFormEdit viewModel)
{
if (ModelState.IsValid)
{
viewModel.PopulateCheckBoxsToScores();
_db.Entry(viewModel.ScoreInstance).State = System.Data.EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("/");
}
else
{
return View(viewModel);
}
}
Here is my viewModel:
public class AuditFormEdit
{
public Models.Score ScoreInstance { get; set; }
public List<ScoreCardCheckBoxHelper> ScoreCardCheckBoxHelperList { get; set; }
public void InitializeScoreCheckBoxHelperList(List<Models.Score> ScoreList)
{
if (this.ScoreCardCheckBoxHelperList == null)
this.ScoreCardCheckBoxHelperList = new List<ScoreCardCheckBoxHelper>();
if (ScoreList != null
&& this.ScoreInstance != null)
{
this.ScoreCardCheckBoxHelperList.Clear();
ScoreCardCheckBoxHelper spacerProductCheckBoxHelper;
string spacerTypes =
string.IsNullOrEmpty(this.ScoreInstance.ScoreName) ?
string.Empty : this.ScoreInstance.ScoreName;
foreach (Models.Score scoreType in ScoreList)
{
spacerProductCheckBoxHelper = new ScoreCardCheckBoxHelper(scoreType);
if (spacerTypes.Contains(scoreType.ScoreName))
spacerProductCheckBoxHelper.Checked = true;
this.ScoreCardCheckBoxHelperList.Add(spacerProductCheckBoxHelper);
}
}
}
public void PopulateCheckBoxsToScores()
{
this.ScoreInstance.ScoreName = string.Empty;
var scoreType = this.ScoreCardCheckBoxHelperList.Where(x => x.Checked)
.Select<ScoreCardCheckBoxHelper, string>(x => x.ScoreName)
.AsEnumerable();
this.ScoreInstance.ScoreName = string.Join(", ", scoreType);
}
public class ScoreCardCheckBoxHelper : Models.Score
{
public bool Checked { get; set; }
public ScoreCardCheckBoxHelper() : base() { }
public ScoreCardCheckBoxHelper(Models.Score scoreCard)
{
this.ScoreID = scoreCard.ScoreID;
this.ScoreName = scoreCard.ScoreName;
}
}
}
Here is the link and controller that pulls the page up this is the Body of the layout:
public ActionResult Audit(int id)
{
var auditToDetail = _db.AuditSchedules.Single(r => r.AuditScheduleID == id);
return View(auditToDetail);
}
the link looks like this:
/AuditSchedule/Audit/257
Let me know if you need anything else.
I have used a code first approach and all tables have models with the relationships called out.
thank you
Your question is pretty general - but here are some things to think about.
First, in MVC3 you typically want to strongly type your views to your models. In your case you would want a single view for each model. You don't want "multiple multiple models in a view", but rather multiple views rendered together on a single page - all linked by some common data.
One way to accomplish this would be set write a "child actions" (use:[ChildActionOnly] attribute) in your controller for populating each of your individual models sending them to their respective indiviudal views. You can use the [Html.RenderAction][3] function within any view to render any other view. The easiest way to organize this is often with layouts 4 - You could render all your views using Html.RenderAction(), and then render your main form as the primary view (displayed in the layout with #RenderBody()).
To populate each of your models you will likely need to know some data (like an id), these can be stored in the ViewBag or ViewData, and passed in as objects in the Html.RenderAction function. (If you are using razor the call in your view might look something like:#{Html.RenderAction("actionName", new {object1 = "xyz", object2 ="abc"});} Just to make this clear, the logical flow will look like this
Populate the ViewBag with the data you will need to render your sub-views,
Populate your model for the main form and you call the main form's view (your primary view).
Your primary view defines a layout view, which in-turn calls Html.RenderAction, using the ViewBag data to set the appropriate objects.
The layout also renders the primary view as the "body" (#RenderBody()).
The end result of this is views that can be [strongly typed][7] to individual views, and individual controller actions for each model. This is a good thing, because it makes your views reusable anywhere, and it isolates the logic for populating each model (because each model has its own action in the controller). If you make subsequent changes to a model, it will be easy to know which Action/Model/View needs to be modified.
Below are some resources to get you started in understanding your options for rendering multiple models on a single page. I apologize for not lacing this post with nice links to helpful items, but as a new answerer, I was limited to two... Google will have to be your guide for the others.
Hope this helps - Best of Luck!
Resources:
Html.RenderAction and Html.Action - http://haacked.com blog
When to use Html.RenderPartial and Html.RenderAction in ASP.NET MVC Razor Views - http://www.arrangeactassert.com

how i can got the value who are define n times in the form in ASP.NET MVC?

i have a form where user fill the n time a information using add another textbox and fill them.
i put the name them as
textbox_1
textbox_2
now how i can got all form values who are start with textbox_1. any idea to do it in asp.net mvc
you can get the value of this text box using javascript and save it in hidden field as comma separated then read the hidden field value from your action method(I am using jquery)
var AllTextBoxesInPage = $('input[type=text]');
var AllValues='';
AllTextBoxesInPage.each(function(index){
if(index==0)
{
AllValues+=',';
}
AllValues+=$(this).val();
});
$('#HiddenFieldID').val(AllValues);
in your controller class
public ActionResult MyAction(FormCollection MyForm)
{
String AllValues =MyForm["HiddenFieldName"];
String[] SeparatedValuse = AllValues.Split(",");
}
Alternatively, you can use BeginCollection from steve sanderson and optionally you can have a look at master detail form

search and result in asp.net mvc c#

i have a textbox with button search.
i would like to search my database of input text from textbox and give result out in one view.
Could you please give me link or help me how its possible to implement?
I have no idea what i shoul to do that.
If you want to show the result in the same view page as that of the search criteria text box, the better approach will be to go with JQuery form post. And from the corresponding controller you can get back the JSON result and bind it to the grid, if you are using any third party grid.
The posting mechanism will be :
<div>
<input type="text" id="txtSearchText" value=""/>
<input type="button" id="btnSearch" value="Search"/>
</div>
<script type="text/javascript">
$("#btnSearch").click(function(){
var formPost={ SearchText : $("#txtSearchText").val()};
//The above SearchText parameter name should be same as property name in the Model class.
$.post("/SearchController/Search",formPost,function(data){
if(data)
{
//Here based on your development methodology, either build a table by
//appending a row for each result Or bind to a grid, if you are using
//any third party control
}
});
});
</script>
Controller Code :
public class SearchController
{
public ActionMethod Search(SearchModel searchCriteria)
{
SearchResultModel result= //Get the search results from database
return new JsonResult{Data=result};
}
}
Model class:
public class SearchModel
{
public string SearchText{get;set;};
}

Ajax.BeginForm inside Html.BeginForm

I have a view that is used for editing stuff, say Orders. Orders have line items that can be added arbitrarily. So a main view and nested partialviews.
Each partial should have an ajax form for tweaking quantities of each line item or whatever.
Thus:
Html.BeginForm()
{%>
Ship to: blah blah blah
<%
Ajax.BeginForm("EditLineItem", "Order", new { OrderLineItemID = Model.ObjectID }, itemAjaxOptions))
{
Item qty blah blah blah
<--! (ajax form's submit button, etc.)-->
}
%>
<--! (ajax form's submit button, etc.)-->
<%
}
I have a controller that looks like this:
[ActionName("Edit")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Edit(int orderID)
{
blah, blah
}
[ActionName("EditLineItem")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult EditLineItem(Guid orderLineItemID)
{
blah, blah
}
My trouble is that when I submit the Ajax form, I get the Edit method instead of the EditLineItem methods. Both routes are mapped. Is there some gotcha like "you can't submit an Ajax form inside of an Html form" that I don't know about?
I tried the exact same thing a while ago. No matter what I did, it wouldn't do the AJAX submit. So I think the answer is: yes, you can't put a submit button for an AJAX form inside a regular html form.
But, why would you have partial submits merged with full submits?
The easiest workaround to this imo would be to use JSON requests with jQuery.
for instance, updating a quantity span text when you change a dropdownlist (id=Order):
<script type="text/javascript">
$(document).ready(function() {
$('select#Order').change(function() {
$.getJSON('/Orders/UpdateQty/' + this.value, {},
function(data) {
$('#qty').html(data);
});
});
});
</script>
And the code in the "Orders" controller:
public class OrdersController : Controller
{
public ActionResult UpdateQty(int id)
{
return Json(yourLibrary.getQuantities(id));
}
}
This Link might help.
Regards
Edit:
So.. the link no longer exists. But thanks to the internet wayback machine, we have this copy :)
AFAIA the AjaxForm is still renders as a form tag, so you'd be nesting forms, which as you've found is a no no.
I reckon Francisco is on the right lines (tho I'd suggest implementing a post rather than a get as you are updating something).
Kind regards,
TP

Categories