Im new at Asp.Net MVC3, and i was trying to use CKEditor. But can't get my typed text then i push submit.
My View:
<form method=post action="#Url.Action("Description")">
<textarea class="ckeditor" id="editor1" rows="10" name="Details">#Resources.Resources.DescriptionSampleText</textarea>
<input type="submit" />
</form>
And the controller there i need the text:
[HttpPost]
public ActionResult Description(string textdetails)
{
//Doing something with the text
return RedirectToAction("Create", "Project", new { text = textdetails});
}
What am I doing wrong?
There are three solutions to your problem. I will start of with solving it directly (two ways), however, in my opinion it is not the best way. Anyway, more about that later.
ASP.NET MVC (3) works a lot convention-based. It will magically assign values etc. from requests to parameters and other. Of course, these conventions are obviously based upon the names of your parameters. You'll have to make sure that your names match (as you might figure out right now, this will be a pain-in-the-a to maintain).
The quick solution is to name your textarea in your view the same as your parameter of your HttpPost action. Your view code would look like this:
<form method=post action="#Url.Action("Description")">
<textarea class="ckeditor" id="editor1" rows="10" name="Textdetails">#Resources.Resources.DescriptionSampleText</textarea>
<input type="submit" />
</form>
This should work. Note: I didn't test this myself right now, however many beginners guides do this as well, so I figure that will work. Anyway, I really don't like this solution, because it is really a hell to maintain (refactoring etc won't be very easy).
A second solution is to use a FormCollection. You give this as a parameter of your HttpPost action and you can access then your value through an index. For an example and more information, you can look at this SO post: https://stackoverflow.com/a/5088493/578843 .
The last solution (which I prefer) is creating a ViewModel. I suggest you read this guide ( http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/examining-the-edit-methods-and-edit-view ) on how to do edit pages etc properly.
And one last thing, if you want to submit HTML as content, you will have to either disable the save guarding of ASP.NET or add a Annotation to your method (or class). Please do not generally disable save guards (it will check input for html etc), only disable it with annotations when needed. You can set the ValidateInput attribute (MSDN link) to false on your action. Example:
[HttpPost]
[ValidateInput(false)]
public ActionResult Description(string textdetails)
{
//Doing something with the text
return RedirectToAction("Create", "Project", new { text = textdetails});
}
Related
I am working on Mobile Store Management System's Order page. I want to allow users to select a company through a select list, and then select multiple models of that company from another select list which is loaded dynamically through AJAX.
The code for the cascading models is working, but I am unable to send the selected models to the server because it is adding them in the DOM through JavaScript.
The following is the code for the cascading selection:
<div class="form-group row">
<label class="control-label col-6">Company Name</label>
<div class="col-12">
<select id="CompanyId" class="custom-select mr-sm-2"
asp-items="#(new SelectList(
#ViewBag.Companies,"Phoneid","Com_name"))">
<option value="">Please Select</option>
</select>
</div>
<span class="text-danger"></span>
</div>
<div class="form-group row">
<label class="control-label col-6"></label>
<div class="col-12">
<select id="modelId" multiple class="custom-select mr-sm-2"
asp-items="#(new SelectList(string.Empty,"modelId","model_name","--Select--"))">
<option value="">Please Select</option>
</select>
</div>
<span class="text-danger"></span>
</div>
<div>
<input type="button" id="saveBtn" value="Save" />
</div>
Cascading Code:
$("#CompanyId").change(async function()
{
await $.getJSON("/Order/GetAllModels",{ PhoneId: $("#CompanyId").val()},
function(data)
{
$("#modelId").empty();
$.each(data, function (index, row) {
$("#modelId").append("<option value='" + row.modelId + "'>" +
row.model_name + '</option>')
});
});
}
Once the Save button is clicked, I am displaying the product for the currently selected models using a partial view:
$('#saveBtn').click(function () {
$.ajax({
url: '/Order/GetProduct?Phoneid=' + $("#CompanyId").val() + "&modelId=" + $('#modelId').val(),
type: 'Post',
success: function (data) {
$('#products').append(data);
},
})
})
Problem 1
When the user selects the first company and their two models, and then clicks the Save button, the partial view loads with indexes i=0,i=1. Then, the user selects another company and selects their models. Again, the partial view renders with same indexes. How can I make the indexes unique? This partial view is rendered when the user clicks the Save button, which renders only the current company's selected models.
#model List<Mobile_Store_MS.ViewModel.Orders.Products>
<table class="table">
<tbody>
#for (int i = 0; i < Model.Count; i++)
{
<tr class="card d-flex">
<td>
<input asp-for="#Model[i].isSelected" />
</td>
<td>
<input hidden asp-for="#Model[i].Phoneid" /> <input hidden asp-for="#Model[i].modelId" />
#Html.DisplayFor(modelItem => Model[i].com_Name) #Html.DisplayFor(modelItem => Model[i].model_name)
</td>
<td>
<input asp-for="#Model[i].Quantity" />
</td>
<td>
<input class="disabled" readonly asp-for="#Model[i].price" />
</td>
</tr>
}
</tbody>
</table>
Problem 2
How can I send all of the items rendered through the partial view to the server? I just want to send these selected products along with the quantity and price for each model to the server. This means binding these items in the product list of the OrderViewModel.
You can find my OrderViewModel and Products model in the following diagram:
Can you tell me how to bind Razor items into a list to post to the controller? I would be very grateful if you give me some suggestions.
Related
Link of my Previous Question
Sample of my order page
TL;DR: Instead of relying on the asp-for tag helper, you can set your own name attribute. This gives you the flexibility to start the index at whatever number you want. Ideally, you will pass the number of existing products to GetProduct() and start indexing off of that. In addition, you also need to prefix your name attribute with Products, thus ensuring those form elements are properly bound to your OrderViewModel.Products collection on post back.
<input name="Products[#(startIndex+i)].Quantity" value="#Model[i].Quantity" />
You can then filter the OrderViewModel.Products collection on the server-side using LINQ to limit the results to selected products:
var selectedProducts = c.Products.Where(p => p.IsSelected);
For a more in-depth explanation of how this approach works, as well as some of the variations in the implementation, read my full answer below.
Detailed Answer
There's a lot going on here, so this is going to be a lengthy answer. I'm going to start by providing some critical background on how ASP.NET Core MVC connects the dots between your view model, your view, and your binding model, as that will better understand how to adapt this behavior to your needs. Then I'm going to provide a strategy for solving each of your problems.
Note: I'm not going to write all of the code, as that would result in me reinventing a lot of code you've already written—and would make for an even longer answer. Instead, I'm going to provide a checklist of steps needed to apply the solution to your existing code.
Background
It's important to note that while ASP.NET Core MVC attempts to standardize and simplify the workflow from view model to view to binding model through conventions (such as the asp-for tag helper) these are each independent of one another.
So when you call asp-for on a collection using e.g.,
<input asp-for="#Model[i].Quantity" />
It then outputs the something like the following HTML:
<input id="0__Quantity" name="[0].Quantity" value="1" />
And then, when you submit that, the server looks at your form data, and uses a set of conventions to map that data back to your binding model. So this might map to:
public async Task<IActionResult> ProductsAsync(List<Product> products) { … }
When you call asp-for on a collection, it will always start the index at 0. And when it bind the form data to a binding model, it will always start at [0] and count up.
But there's no reason you need to use asp-for if you need to change this behavior. You can instead set the id and/or name attributes yourself if you need flexibility over how they are generated.
Note: When you do this, you'll want to make sure you're still sticking to one of the conventions that ASP.NET Core MVC is already familiar with to ensure data binding occurs. Though, if you really want to, you can instead create your own binding conventions.
Problem 1: Setting the index
Given the above background, if you want to customize the starting index returned from your call to GetProducts() for your second model, you‘ll want to do something like the following:
Before calling GetProduct(), determine how many products you already have by e.g. counting the number of elements with the card class assigned (i.e., $(".card").length).
Note: If the card class is not exclusively used for products, you can instead assign a unique class like product to each tr element in your _DisplayOrder view and count that.
Include this count in your call to GetProduct() as e.g., a &startingIndex= parameter:
$('#saveBtn').click(function () {
$.ajax({
url: '/Order/GetProduct?Phoneid=' + $("#CompanyId").val() + "&modelId=" + $('#modelId').val() + "&startingIndex=" + $("#card").length,
type: 'Post',
success: function (data) {
$('#products').append(data);
},
})
})
[HttpPost]
public IActionResult GetProduct(int Phoneid, string[] modelId, int startingIndex = 0) { … }
Relay this startingIndex to your "partial" view via a view model; e.g.,
public class ProductListViewModel {
public int StartingIndex { get; set; }
public List<Product> Products { get; set; }
}
Use that value to offset the index written to the output:
<input id="#(Model.StartingIndex+i)__Quantity" name="[#(Model.StartingIndex+i)].Quantity" value="#Model.Products[i].Quantity" />
That's not as tidy as asp-for since you're needing to wire up a lot of similar information, but it offers you the flexibility to ensure that your name values are unique on the page, no matter how many times you call GetProduct().
Notes
If you don't want to create a new view model, you could relay the startingIndex via your ViewData dictionary instead. I prefer having a view model that includes all of the data I need, though.
When using the asp-for tag helper, it automatically generates the id attribute, but if you're not ever referencing it via e.g. JavaScript you can omit it.
Browsers will only submit values to the server for form elements that have a name attribute. So if you have input elements that are needed on the client-side but aren't needed in the binding model, for some reason, you can omit the name attribute.
There are other conventions besides {Index}__{Property} that you can follow. But unless you really want to get into the weeds of model binding, you're best off sticking to one of the existing collection conventions.
Be careful of your indexing!
In the Model Binding conventions for collections, you'll notice a warning:
Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. If there are any gaps in subscript numbering, all items after the gap are ignored. For example, if the subscripts are 0 and 2 instead of 0 and 1, the second item is ignored.
As such, when assigning these, you need to make sure that they're sequential without any gaps. If you're using the count (.length) of existing e.g. $(".card") or $(".product") elements on your page to seed the startingIndex value, however, then that shouldn't be a problem.
Problem 2: Sending these values to the server
As mentioned above, any form element with a name attribute will have its data submitted to the server. So it doesn't really matter if you're using asp-for, writing out your form manually using HTML, or constructing it dynamically using JavaScript. If there's a form element with a name attribute, and it's within the form being submitted, it will get included in the payload.
Debugging your form data
You're likely already familiar with this, but if not: If you use your browser's developer console, you'll be able to see this information as part of the page metadata when you submit your form. For instance, in Google Chrome:
Go to Developer Tools (Ctrl+Shift+I)
Go to the Network tab
Submit your form
Click on the name of your page (normally the first entry)
Go to the Headers tab
Scroll down to the Form Data section (or Query String Parameters for a GET request)
You should see something like:
[0].isSelected true
[0].Phoneid 4
[0].modelId 10
[0].Quantity 5
[0].price 10.50
[1].isSelected true
[…]…
If you're seeing these in Chrome, but not seeing these data reflected in your ASP.NET Core MVC controller action, then there's a disconnect between the naming conventions of these fields and your binding model—and, thus, ASP.NET Core MVC doesn't know how to map the two.
Binding Problems
There are two likely issues here, both of which might be interfering with your data binding.
Duplicate Indexes
Since you are currently submitting duplicate indexes, that could be causing collisions with the data. E.g., if there are two values for [0].Quantity, then it will retrieve those as an array—and may fail to bind either value to e.g. the int Quantity property on your Products binding model. I haven't tested this, though, so I'm not entirely sure how ASP.NET Core MVC deals with this situation.
Collection Name
When you bind to a List<Products> with the asp-for tag helper, I believe it will use the [i].Property naming convention. That's a problem because your OrderViewModel is not a collection. Instead, these needs to be associated with the Products property on your binding model. That can be done by prefixing the name with Products. This will be done automatically if you use asp-for to bind to a Products property on your view model—as proposed on the ProductListViewModel above. But since you need to dynamically generate the name's based on the IndexOffset anyway, you can just hard-code these as part of your template:
<input id="Products_#(Model.StartingIndex+i)__Quantity" name="Products[#(Model.StartingIndex+i)].Quantity" value="#Model.Products[i].Quantity" />
Selected Products
There's still a problem, though! This is going to include all of your products—even if they weren't otherwise selected by the user. There are a number of strategies for dealing with this, from dynamically filtering them on the client, to creating a custom model binder that first validates the Products_[i]__isSelected attribute. The easiest, though, is to simply allow all of them to be bound to your binding model, and then filter them prior to any processing using e.g. LINQ:
var selectedProducts = c.Products.Where(p => p.IsSelected).ToList();
…
repo.SetProducts(selectedProducts);
For the 1st question, you can try different things. When you do the ajax call, you get a list of models. For each of these models, add the selected company ID as a property. So you don't have to worry about the index being something unique.
As for the 2nd question, should be a relatively easy thing to do. However, more information is needed.
1. When the save button is hit, are you doing a full postback? or it is also an AJAX call?
2. Why do you not want to opt for a AJAX call to do the update as well? So you can based upon the response, redirect the user to a results page, etc.
If you can create a small sample in a new project, and upload to github, and post the information here. I should be able to take a look and understand better. I will definitely be able to help.
Also try reading this thread, it might help
how to persist partial view model data during postback in asp.net mvc
I've been working on a small school project and decided to use .net core (MVC) for the first time. I have a small button I can click which executes the "ipconfig" command in the background and displays the output in a text area. At first my team partner used only a
public string Result;
in ViewModel for the view. In the view it's displayed via
<textarea asp-for="Result"></textarea>
So I decided to make it into a property with default get and set:
public string Result { get; set; }
But when I do that, the output doesn't show up in the textarea if I keep the same approach in the view as my team member did when he used a field instead of a property. Instead I have to do it like this to get it to show up in the textarea:
<textarea>#Model.Result</textarea>
Now I'm asking myself why this happens. Can't I display Properties with asp-for? And what would be better to use, a field or a property as Result?
Many thanks in advance!
In my case this behavior was happening because I did not have a separate closing tag on my textarea. I know your example above has it when using the asp-for method, but in case that was a copy/paste error, you may want to look at that again.
<textarea asp-for="Message" type="text" class="form-control" rows="5" id="MessageInputField" autofocus></textarea>
As opposed to:
<textarea asp-for="Message" type="text" class="form-control" rows="5" id="MessageInputField" autofocus />
This is incredibly annoying 'gotcha' like behavior in my opinion. And maybe if someone wants to tell me why it isn't, then please enlighten me, I'm always willing to learn.
You should actually be using properties, and if <textarea>#Model.Result</textarea> works, <textarea asp-for="Result"></textarea> should as well. The only reason it wouldn't is if the ModelState has a different value for Result (as the latter form actually uses ModelState, whereas the former is obviously using Model directly).
ModelState is composed of values from Request, ViewData/ViewBag, and finally Model, so for example, if you were to do something like ViewBag.Result = String.Empty, that would actually override the value from Model in ModelState.
There's no enough code here to truly diagnose the exact issue, but I would look for other places you might be using "result" (case-insensitive). If you're accepting that as a request param or setting a ViewBag member, etc. that's your problem.
I find this is a bit weird in .Net Core 6, when I want two-way binding - ie displaying the result
With asp-for I have to self close the tag AND add the additional textarea close tag to get the result displayed.
<textarea asp-for="Result" />#Model.Result</textarea>
This works but is not syntactically correct.
Without the self-close tag, the result was not being display
<textarea asp-for="Result">#Model.Result</textarea> #*Does not display the value*#
For display only, this is more correct
<textarea>#Model.Result</textarea>
So I am trying to set up a website that has questions, answers, and comments, much like stackoverflow. right now, I am trying to get comments to work correctly. I have decided that I will try to use an ActionLink to send the comment text to the controller. Is there any way that you can do this without invoking the model fields?
Use a simple form submit, then grab your submitted data via a FormCollection
[HttpPost]
public ActionResult SubmitComment(FormCollection collection)
{
string comment = collection["comment"];
}
and for your view
#using (Html.BeginForm("SubmitComment", "CommentsController"))
{
#Html.TextBox("comment")
<input type="submit" value="submit" />
}
In my opninon you are better off binding this data to a model in the long run. See this link for more details : Is there any good reason to use FormCollection instead of ViewModel?
What if you place your inputs to <form> tag ?
#using (Html.BeginForm("AddComent", "CommentsController"))
{
#Html.TextBox("comment")
<input type="submit" value="Post Your Comment" />
}
P.S.
Other option (that i prefer) would be to send Ajax Post calls with JQuery: $.post("#Url.Action("$Action", "$Controller")", { $parameter: $data });
I have a C# MVC application and a <form> in my page.cshtml file. In that form I have <input type="text" ... /> elements. If I submit this form I only get the values in Response.Params or Response.Form from the inputs where I changed the value manually (i.e. Entered the text box then typed something).
If I change the value with jQuery, $('#myInput').val('some value'); this does not count as a change in the input's value and I do not get myInput's value when I submit the form.
Is there any way to make sure all inputs are submitted? If not then is there a good workaround for this, maybe in some event that occurs before my model gets bound? I need to know all the input values from the form when submitted whether they changed or not.
Some additional info:
The form and other values are getting submitted correctly and I am receiving my model when the POST action is called in my controller.
The real issue is when my model is being bound. It is being created and bound with all values except the one not being submitted because it is not in the Request.Params collection.
I have only ever seen this behaviour when a field is disabled. Due to this, I commonly have a javascript function that handles the form submission and re-enables them on submit, this way the correct values get sent to the server.
Something like this does the trick for me (NOTE: I am using JQuery):
$(document).ready() {
$("#ButtonSubmit").click(SubmitForm);
}
function SubmitForm(e) {
e.preventDefault();
//ensure fields are enabled, this example does text and checkbox types
$("[type='text']").attr("disabled", false);
$("[type='checkbox']").attr("disabled", false);
//submit the form
document.forms[0].submit();
}
I am unaware of any easier way to do this, it would be nice if you could 'flag' something that instructs all fields to be submitted. But I don't know if this exists, maybe somebody else can offer a better solution.
EDIT: It appears that disabled fields not submitting is just the nature of HTML, and is not something that is tied to MVC.
It seems that if you make the fields readonly instead of disabled then the values will still submit. However, with this approach you lose the 'disabled' styling. The exception to this rule is select control, it seems this will not submit under readonly either. More information on this can be in this question
Try using the razor helper to build the form tag.
#using(Html.BeginForm()) {
..
// make sure this is a submit button
<input type="submit" value="Save" />
}
In your controller action post method make sure you decorate it [HttpPost].
e.g.,
[HttpPost]
public ActionResult Edit(YourModel model) {
}
Something pretty weird is happening with my app:
I have the following property in my ViewModel:
public int? StakeholderId { get; set; }
It gets rendered in a partial view as follows:
<%= Html.Hidden("StakeholderId", Model.StakeholderId) %>
The form is submitted, and the relevant controller action generates an id and updates the model, before returning the same view with the updated model
The problem I'm experiencing is that the hidden field does not have anything in its "value" attribute rendered the second time even though StakeholderId now has a value.
If I just output the value on its own, it shows up on the page, so I've got it to render the value by doing this:
<input type="hidden" id="StakeholderId" name="stakeholderId" value="<%: Model.StakeholderId %>" />
But it's pretty strange that the helper doesn't pick up the updated value?
(I'm using jQuery to submit forms and render the action results into divs, but I've checked and the html I get back is already wrong before jQuery does anything with it, so I don't think that has much to do with anything)
UPDATE
I've since discovered that I can also clear the relevant ModelState key before my controller action returns the partial view.
The helper will first look for POSTed values and use them. As you are posting the form it will pick up the old value of the ID. Your workaround is correct.
ADDENDUM: Multiple HTML Forms, eg, in a Grid
As an addendeum to this issue, one thing to be VERY careful of is with multiple forms on the same page, eg, in a grid, say one generated using Ajax.BeginForm.
You might be tempted to write something along the lines of:
#foreach (var username in Model.TutorUserNames)
{
<tr>
<td>
#Html.ActionLink(username, MVC.Admin.TutorEditor.Details(username))
</td>
<td>
#using (Ajax.BeginForm("DeleteTutor", "Members",
new AjaxOptions
{
UpdateTargetId = "AdminBlock",
OnBegin = "isValidPleaseWait",
LoadingElementId = "PleaseWait"
},
new { name = "DeleteTutorForm", id = "DeleteTutorForm" }))
{
<input type="submit" value="Delete" />
#Html.Hidden("TutorName", username)
}
</td>
</tr>
}
The lethal line in here is:
#Html.Hidden("TutorName", username)
... and intend to use TutorName as your action's parameter. EG:
public virtual ActionResult DeleteTutor(string TutorName){...}
If you do this, the nasty surprise you are in for is that Html.Hidden("TutorName", username) will, as Darin Dimitrov explains, render the last POSTed value. Ie, regardless of your loop, ALL the items will be rendered with the TutorName of the last deleted Tutor!
The word around, in Razor syntax is to replace the #Html.Hidden call with an explicit input tag:
<input type="hidden" id="TutorName" name="TutorName" value='#username' />
This works as expected.
Ie:
NEVER, EVER USE Html.Hidden TO PASS A PARAMETER BACK TO YOUR ACTIONS WHEN YOU ARE USING MULTIPLE FORMS IN A GRID!!!
Final Caveat:
When constructing your hidden input tag, you need to include both name and id, set to the same value, otherwise, at the time of writing (Feb 2011) it won't work properly. Certainly not in Google Chrome. All you get is a null parameter returned if you only have an id and no name attribute.